<?php
namespace App\Api\Controllers\Export;


use App\Api\Controllers\BaseController;
use App\Models\MerchantStore;
use App\Models\Order;
use App\Models\Store;
use App\Models\User;
use App\Models\UserRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class OrderExportController extends BaseController
{

    //商户导出
    public function MerchantOrderExcelDown(Request $request)
    {
        $merchant = $this->parseToken();
        $store_id = $request->get('store_id', '');
        $merchant_id = $request->get('merchant_id', '');
        $pay_status = $request->get('pay_status', '');
        $ways_source = $request->get('ways_source', '');
        $ways_type = $request->get('ways_type', '');
        $time_start_s = date('Y-m-d 00:00:00', time());
        $time_start_e = date('Y-m-d 23:59:59', time());

        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');

        if (in_array($time_start,[null,''])){
            $time_start=$time_start_s;
        }

        if (in_array($time_end,[null,''])){
            $time_end=$time_start_e;
        }

        $out_trade_no = $request->get('out_trade_no', '');
        $trade_no = $request->get('trade_no', '');
        $where_desc = '';

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        $now_time = date('Y-m-d H:i:s', time());
        $end = date('Y-m-d 22:00:00', time());
        if ($now_time > $end) {
            $day = 31;
        }

        if ($date > $day) {
           echo '时间筛选不能超过' . $day . '天';
           dd();
        }

        //跨天操作
        $time_start_db = date('Ymd', strtotime($time_start));
        $time_end_db = date('Ymd', strtotime($time_end));;
        $is_ct_time=0;
        if ($time_start_db != $time_end_db) {
            $is_ct_time=1;
        }

        $MerchantOrderExcelDown = Cache::get('ExcelDown');
        if ($MerchantOrderExcelDown) {
            //echo 'a正在生成数据请1分钟后再来操作';
            //die;
        } else {
            Cache::put('ExcelDown', '1', 1);
        }

        $where = [];
        $store_ids = [];
        if ($out_trade_no && $out_trade_no != "undefined") {
            $where[] = ['out_trade_no', 'like', '%' . $out_trade_no . '%'];
            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
        }

        if ($trade_no && $trade_no != "undefined") {
            $where[] = ['trade_no', 'like', '%' . $trade_no . '%'];
            $where_desc = $where_desc . ';订单编号：' . $trade_no;
        }

        //收银员
        if ($merchant->merchant_type == 2) {
            $where[] = ['merchant_id', '=', $merchant->merchant_id];
            $where_desc = $where_desc . ';收银员ID：' . $merchant->merchant_id;
        }

        //是否传收银员ID
        if ($merchant_id) {
            $where[] = ['merchant_id', '=', $merchant_id];
            $where_desc = $where_desc . ';收银员ID：' . $merchant->merchant_id;
        }
        if ($pay_status) {
            $where[] = ['pay_status', '=', $pay_status];
            $where_desc = $where_desc . ';支付状态：' . $pay_status;
        }
        if ($store_id) {
            $store_ids = [
                [
                    'store_id' => $store_id,
                ]
            ];
        } else {
            $MerchantStore = MerchantStore::where('merchant_id', $merchant->merchant_id)
                ->select('store_id')
                ->get();

            if (!$MerchantStore->isEmpty()) {
                $store_ids = $MerchantStore->toArray();
            }
        }
        if ($ways_source) {
            $where[] = ['ways_source', '=', $ways_source];
            $where_desc = $where_desc . ';支付方式：' . $ways_source;
        }
        if ($ways_type) {
            $where[] = ['ways_type', '=', $ways_type];
            $where_desc = $where_desc . ';支付类型：' . $ways_type;
        }
        if ($time_start) {
            $time_start = date('Y-m-d H:i:s', strtotime($time_start));
            $where[] = ['created_at', '>=', $time_start];
            $where_desc = $where_desc . ';订单开始时间：' . $time_start;
        }
        if ($time_end) {
            $time_end = date('Y-m-d H:i:s', strtotime($time_end));
            $where[] = ['created_at', '<=', $time_end];
            $where_desc = $where_desc . ';订单结束时间：' . $time_end;
        }

        $day = date('Ymd', strtotime($time_start));
        $table = 'orders_' . $day;
        if (env('DB_D1_HOST')) {
            //有没有跨天
            if ($is_ct_time) {
                if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                    $obj = DB::connection("mysql_d1")->table('order_items');
                } else {
                    $obj = DB::connection("mysql_d1")->table('orders');
                }
            } else {
                if (Schema::hasTable($table)) {
                    $obj = DB::connection("mysql_d1")->table($table);
                } else {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                }
            }
        } else {
            if ($is_ct_time) {
                if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                    $obj = DB::table('order_items');
                } else {
                    $obj = DB::table('orders');
                }
            } else {
                if (Schema::hasTable($table)) {
                    $obj = DB::table($table);
                } else {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                }
            }
        }
        
         //采蝶轩
        if ($merchant->merchant_id == '10377') {
            
            //根据交易时间判断
            $trading_time_start = $request->get('trading_time_start');
            $trading_time_end = $request->get('trading_time_end');
            if ($trading_time_end || $trading_time_start) {
                if ($trading_time_start) {
                    $trading_time_start = date('Y-m-d H:i:s', strtotime($trading_time_start));
                    $where[] = ['pay_time', '>=', $trading_time_start];
                } else {
                    $trading_time_start = date('Y-m-d 00:00:00');
                    $where[] = ['pay_time', '>=', date('Y-m-d 00:00:00')];
                }
                if ($trading_time_end) {
                    $trading_time_end = date('Y-m-d H:i:s', strtotime($trading_time_end));
                    $where[] = ['pay_time', '<=', $trading_time_end];
                } else {
                    $trading_time_end = date('Y-m-d 23:59:59');
                    $where[] = ['pay_time', '<=', date('Y-m-d 23:59:59')];
                }
                $tradingDiff = (strtotime($trading_time_end) - strtotime($trading_time_start)) / 86400;
                $newWhere = [];
                foreach ($where as  $wv) {
                    if (!in_array('created_at', $wv)) {
                        $newWhere[] = $wv;
                    }
                }
                $where = $newWhere;
                if ($tradingDiff > 31 || $tradingDiff < 0) {
                    return json_encode([
                        'status' => 2,
                        'message' => '交易时间大于31天或结束时间小于开始时间'
                    ]);
                }
            }
             error_log(date('Y-m-d H:i:s')." 【导出查询】： ".json_encode([$where,$store_ids])."\n\n", 3, "/tmp/". 'export'.date('Ymd').".log");
            $sids = [];
            foreach ($store_ids as $sid) {
                $sids[] = (int)$sid['store_id'];
            }
            $store_ids = array_unique($sids);
            $newOrder = $obj->where($where)->whereIn('store_id', $store_ids)
                ->selectRaw('orders.store_id')
                ->selectRaw('orders.store_name')
                ->selectRaw('orders.merchant_name')
                ->selectRaw('0 trading_type')
                ->selectRaw('0 refund_no')
                ->selectRaw('orders.out_trade_no')
                ->selectRaw('orders.qwx_no')
                ->selectRaw('orders.other_no')
                ->selectRaw('orders.total_amount')
                ->selectRaw('0 refund_amount')
                ->selectRaw('orders.rate')
                ->selectRaw('orders.fee_amount')
                ->selectRaw('orders.ways_source_desc')
                ->selectRaw('orders.pay_time as created_at')
                ->selectRaw('orders.remark')
                ->selectRaw('orders.pay_status_desc')
                ->get()->toArray();
               
            foreach ($newOrder as &$nv) {
                $nv->trading_type = '支付';
                $nv->refund_no = '';
                $nv->refund_amount = 0;
                $nv->fee_amount = '-'.$nv->fee_amount;
                $nv->qwx_no = ','.$nv->qwx_no;
                $nv->other_no = ','.$nv->other_no;
            }
             $newWhere = [];
            foreach ($where as  $wv) {
                if (!in_array('pay_status', $wv)) {
                    $newWhere[] = $wv;
                }
                
            }
            foreach ($newWhere as &$wv) {
                if ($wv[0] == 'pay_time') {
                    $wv[0] = 'created_at';
                }
                $wv[0] = 'refund_orders.'.$wv[0];
            }
            $refundOrder = \App\Models\RefundOrder::where($newWhere)
                ->selectRaw('orders.store_id')
                ->selectRaw('orders.store_name')
                ->selectRaw('orders.merchant_name')
                ->selectRaw('0 trading_type')
                ->selectRaw('refund_orders.refund_no')
                ->selectRaw('orders.out_trade_no')
                ->selectRaw('orders.qwx_no')
                ->selectRaw('orders.other_no')
                ->selectRaw('orders.total_amount')
                ->selectRaw('orders.refund_amount')
                ->selectRaw('orders.rate')
                ->selectRaw('orders.fee_amount')
                ->selectRaw('orders.ways_source_desc')
                ->selectRaw('refund_orders.created_at')
                ->selectRaw('orders.remark')
                 ->selectRaw('orders.pay_status_desc')
                ->leftJoin("orders","orders.out_trade_no","=","refund_orders.out_trade_no")
                ->whereIn('refund_orders.store_id', $store_ids)->get()->toArray();

            foreach ($refundOrder as &$rv) {
                $rv['trading_type'] = '退款';
                $rv['qwx_no'] = ','.$rv['qwx_no'];
                $rv['other_no'] = ','.$rv['qwx_no'];
                // $rv['total_amount'] = '-'.$rv['total_amount'];
            }
            // 合并数组
            $newOrder = json_decode(json_encode($newOrder), true);
            $mergedArray = array_merge($newOrder, $refundOrder);
            // 根据年龄（created_at）字段进行排序
            usort($mergedArray, function ($a, $b){
                return strtotime($b['created_at']) - strtotime($a['created_at']);
            });
            $filename = '订单导出.csv';
            $s_array = ['筛选条件：' ]; 
            $tileArray = ['门店ID', '门店名称', '收银员', '交易类型', '退款单号','订单号', '三方订单号', '系统订单号', '订单金额', '退款金额', '费率', '手续费', '支付方式', '交易时间', '备注', '支付状态'];

            return $this->exportToExcel($filename, $s_array, $tileArray, $mergedArray);
        } else if ($merchant->merchant_id == '4776') {
             $dataArray = DB::select("
                    SELECT
	                    store_id,store_name,merchant_name,out_trade_no,total_amount,refund_amount,rate,fee_amount,ways_source_desc,pay_status,pay_status_desc,pay_time,company,remark
                    FROM
                        $table AS o
                        LEFT JOIN merchants AS m ON m.id = o.merchant_id 
                    WHERE
                        o.store_id IN ( SELECT store_id FROM stores WHERE pid = 2943 OR id = 2943 )
	        ");
	        //$dataArray = json_decode(json_encode($dataArray), true));
	        $dataArray = json_decode(json_encode($dataArray), true);
            $filename = '订单导出.csv';
            $s_array = ['筛选条件：' . $where_desc];
            $tileArray = ['门店ID', '门店名称', '收银员', '订单号', '订单金额','退款金额', '费率', '手续费', '支付方式', '支付状态', '支付状态说明', '付款时间', '通道', '备注'];

            return $this->exportToExcel($filename, $s_array, $tileArray, $dataArray);
        } else {
            $dataArray = $obj->where($where)
                ->whereIn('store_id', $store_ids)
                ->orderBy('updated_at', 'desc')
                ->select(
                    'store_id',
                    'store_name',
                    'merchant_name',
                    'out_trade_no',
                    'total_amount',
                    'refund_amount',
                    'rate',//商户交易时的费率
                    'fee_amount',
                    'ways_source_desc',
                    'pay_status',//系统状态
                    'pay_status_desc',
                    'pay_time',
                    'company',//通道方
                    "remark"
                )
                ->get()->map(function ($value) {
                    return (array)$value;
                })->toArray();
            foreach ($dataArray as $k=>$v){
                $dataArray[$k]['refund_time'] = $this->refundTime($v['out_trade_no']);
            }
            $filename = '订单导出.csv';
            $s_array = ['筛选条件：' . $where_desc];
            $tileArray = ['门店ID', '门店名称', '收银员', '订单号', '订单金额','退款金额', '费率', '手续费', '支付方式', '支付状态', '支付状态说明', '付款时间', '通道', '备注', '退款时间'];
    
            return $this->exportToExcel($filename, $s_array, $tileArray, $dataArray);
        }

        
    }

    public function refundTime ($out_trade_no)
    {
        return DB::table('refund_orders')->where(['out_trade_no' => $out_trade_no])->value('created_at');
    }
    
    //门店导出
    public function export_stores(Request $request){
        $is_quota = $request->get('is_quota',0);//
        session_start();
        $token = $this->parseToken();
        $user_id=$token->user_id;
        $user_ids=$this->getSubIds($user_id);
        if($user_id==1){
            // $stores =  DB::table('stores')->where('pid',0)->get();
            if($is_quota == '0'){
                $stores =  DB::table('stores')->where('pid',0)->get();
            }else{
                $stores =  DB::table('stores')->where(['pid' => 0,'is_quota' => $is_quota])->get();
            }
        }else{
            $stores =  DB::table('stores')->where('pid',0)->whereIn('user_id', $user_ids)->get();
        }
        $dataArray=array();
        foreach($stores as $k=>$v){
            $user=DB::table('users')->where('id',$v->user_id)->first();
            if(empty($user)){
                continue;
            }
            unset($_SESSION['users']);
            $users = $this->recursion1($v->user_id);
            $users=json_decode($users,true);
            $users=array_reverse($users);
            $dataArray[$k]['store_id']=$v->store_id. "\t";
            $dataArray[$k]['store_name']=$v->store_name;
            $dataArray[$k]['store_short_name']=$v->store_short_name;
            $dataArray[$k]['people']=$v->people;
            $dataArray[$k]['store_type_name']=$v->store_type_name;
            $dataArray[$k]['user_name']=$user->name;
            $dataArray[$k]['rate']=$v->rata_store*100;
            $dataArray[$k]['store_money']=$v->store_money;
            if($v->rata_status==1){
                $dataArray[$k]['status_name']='预充商户';
            }else{
                $dataArray[$k]['status_name']='非预充商户';
            }
            if(isset($users[0])){
                $dataArray[$k]['level1_name']=$users[0]['name'];
            }else{
                $dataArray[$k]['level1_name']='无';
            }
            if(isset($users[1])){
                $dataArray[$k]['level2_name']=$users[1]['name'];
            }else{
                $dataArray[$k]['level2_name']='无';
            }
            if(isset($users[2])){
                $dataArray[$k]['level3_name']=$users[2]['name'];
            }else{
                $dataArray[$k]['level3_name']='无';
            }
            if(isset($users[3])){
                $dataArray[$k]['level4_name']=$users[3]['name'];
            }else{
                $dataArray[$k]['level4_name']='无';
            }
             if(isset($users[4])){
                $dataArray[$k]['level5_name']=$users[4]['name'];
            }else{
                $dataArray[$k]['level5_name']='无';
            }
            if($v->is_quota==1){
                $dataArray[$k]['is_quota']='开';
            }else{
                $dataArray[$k]['is_quota']='关';
            }
            $dataArray[$k]['created_at']=$v->created_at;
        }
        $s_array=[];
        $filename = '门店列表.csv';
        $tileArray = ['商户ID', '商户名称', '商户简称', '商户联系人', '商户类型', '所属代理','预充费率','预充余额', '是否预充商户','顶级渠道','一级渠道','二级渠道','三级渠道','四级渠道','额度开关','入驻时间'];

        return $this->exportToExcel($filename, $s_array, $tileArray, $dataArray);
    }


    //服务商导出
    public function UserOrderExcelDown(Request $request)
    {
        $user = $this->parseToken();
        $store_id = $request->get('store_id', '');
        $user_id = $request->get('user_id', '');
        $pay_status = $request->get('pay_status', '');
        $ways_source = $request->get('ways_source', '');
        $company = $request->get('company', '');
        $ways_type = $request->get('ways_type', '');
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');
        $amount_start = $request->get('amount_start', ''); //开始金额
        $amount_end = $request->get('amount_end', ''); //结束金额
        $device_id = $request->get('device_id', ''); //设备id
        // print_r($amount_start);die;
        if($amount_start == 'undefined'){
            $amount_start = '';
        }
        if($amount_end == 'undefined'){
            $amount_end = '';
        }

        $time_start_e = date('Y-m-d 23:59:59', time());
        $time_start_s = date('Y-m-d 00:00:00', time());

        if (in_array($time_start,[null,''])){
            $time_start=$time_start_s;
        }

        if (in_array($time_end,[null,''])){
            $time_end=$time_start_e;
        }

        $out_trade_no = $request->get('out_trade_no', '');
        $trade_no = $request->get('trade_no', '');
        $where_desc = '';
        $where = [];

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        $now_time = date('Y-m-d H:i:s', time());
        $end = date('Y-m-d 22:00:00', time());
        if ($now_time > $end) {
            $day = 31;
        }

        if ($date > $day) {
            echo '时间筛选不能超过' . $day . '天';
            dd();
        }

        //跨天操作
        $time_start_db = date('Ymd', strtotime($time_start));
        $time_end_db = date('Ymd', strtotime($time_end));;
        $is_ct_time=0;
        if ($time_start_db != $time_end_db) {
            $is_ct_time=1;
        }

        // $MerchantOrderExcelDown = Cache::get('ExcelDown');
        // if ($MerchantOrderExcelDown) {
        //     echo '正在生成数据请1分钟后再来操作';
        //     die;
        // } else {
        //     Cache::put('ExcelDown', '1', 1);
        // }

        if ($user_id == "") {
            $user_id = $user->user_id;
        }
        $user_ids = $this->getSubIds($user_id);

        $day = date('Ymd', strtotime($time_start));
        $table = 'orders_' . $day;
        
        if (env('DB_D1_HOST')) {
            //有没有跨天
            if ($is_ct_time) {
                if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                    if ($pay_status) {
                        $where[] = ['order_items.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = ['order_items.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = ['order_items.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        $where[] = ['order_items.ways_source', '=', $ways_source];
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = ['order_items.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = ['order_items.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = ['order_items.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = ['order_items.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = ['order_items.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = ['order_items.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = ['order_items.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    $obj = DB::connection("mysql_d1")->table('order_items');
                    $dataArray = $obj->where($where)
                        ->join('users', 'order_items.user_id', '=', 'users.id')
                        ->whereIn('order_items.user_id', $user_ids)
                        ->orderBy('order_items.updated_at', 'desc')
                        ->select(
                            'users.name',
                            'order_items.store_id',
                            'order_items.store_name',
                            'order_items.merchant_name',
                            'order_items.out_trade_no',
                            'order_items.total_amount',
                            'order_items.refund_amount',
                            'order_items.rate',//商户交易时的费率
                            'order_items.fee_amount',
                            'order_items.ways_source_desc',
                            'order_items.pay_status',//系统状态
                            'order_items.pay_status_desc',
                            'order_items.pay_time',
                            'order_items.company',//通道方
                            "order_items.remark"
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                } else {
                    $obj = DB::connection("mysql_d1")->table('orders');
                    if ($pay_status) {
                        $where[] = ['orders.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = ['orders.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = ['orders.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        $where[] = ['orders.ways_source', '=', $ways_source];
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = ['orders.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = ['orders.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = ['orders.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = ['orders.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = ['orders.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    $dataArray = $obj->where($where)
                        ->join('users', 'orders.user_id', '=', 'users.id')
                        ->whereIn('orders.user_id', $user_ids)
                        ->orderBy('orders.updated_at', 'desc')
                        ->select(
                            'users.name',
                            'orders.store_id',
                            'orders.store_name',
                            'orders.merchant_name',
                            'orders.out_trade_no',
                            'orders.total_amount',
                            'orders.refund_amount',
                            'orders.rate',//商户交易时的费率
                            'orders.fee_amount',
                            'orders.ways_source_desc',
                            'orders.pay_status',//系统状态
                            'orders.pay_status_desc',
                            'orders.pay_time',
                            'orders.company',//通道方
                            "orders.remark"
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                }
            } else {
                if (Schema::hasTable($table)) {
                    $obj = DB::connection("mysql_d1")->table($table);
                    if ($pay_status) {
                        $where[] = [ ''.$table.'.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = [ ''.$table.'.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = [ ''.$table.'.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        $where[] = [ ''.$table.'.ways_source', '=', $ways_source];
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = [ ''.$table.'.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = [ ''.$table.'.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = [ ''.$table.'.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = [ ''.$table.'.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = [ ''.$table.'.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = [''.$table.'.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = [''.$table.'.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    $dataArray = $obj->where($where)
                        ->join('users',   ''.$table.'.user_id', '=', 'users.id')
                        ->whereIn(  ''.$table.'.user_id', $user_ids)
                        ->orderBy(  ''.$table.'.updated_at', 'desc')
                        ->select(
                            'users.name',
                            ''.$table.'.store_id',
                            ''.$table.'.store_name',
                            ''.$table.'.merchant_name',
                            ''.$table.'.out_trade_no',
                            ''.$table.'.total_amount',
                            ''.$table.'.refund_amount',
                            ''.$table.'.rate',//商户交易时的费率
                            ''.$table.'.fee_amount',
                            ''.$table.'.ways_source_desc',
                            ''.$table.'.pay_status',//系统状态
                            ''.$table.'.pay_status_desc',
                            ''.$table.'.pay_time',
                            ''.$table.'.company',//通道方
                            ''.$table.'.remark'//
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                } else {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        if ($pay_status) {
                            $where[] = ['order_items.pay_status', '=', $pay_status];
                            $where_desc = $where_desc . ';支付状态：' . $pay_status;
                        }
                        if ($store_id) {
                            $where[] = ['order_items.store_id', '=', $store_id];
                            $where_desc = $where_desc . ';门店ID：' . $store_id;
                        }
                        if ($company) {
                            $where[] = ['order_items.company', '=', $company];
                            $where_desc = $where_desc . ';通道：' . $company;
                        }
                        if ($ways_source) {
                            $where[] = ['order_items.ways_source', '=', $ways_source];
                            $where_desc = $where_desc . ';支付方式：' . $ways_source;
                        }
                        if ($ways_type) {
                            $where[] = ['order_items.ways_type', '=', $ways_type];
                            $where_desc = $where_desc . ';支付类型：' . $ways_type;
                        }
                        if ($time_start) {
                            $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                            $where[] = ['order_items.created_at', '>=', $time_start];
                            $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                        }
                        if ($time_end) {
                            $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                            $where[] = ['order_items.created_at', '<=', $time_end];
                            $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                        }
                        if ($out_trade_no && $out_trade_no != "undefined") {
                            $where[] = ['order_items.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($trade_no && $out_trade_no != "undefined") {
                            $where[] = ['order_items.trade_no', 'like', '%' . $trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($amount_start) {
                            $where[] = ['order_items.total_amount', '>=', $amount_start];
                            $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                        }
                        if ($amount_end) {
                            $where[] = ['order_items.total_amount', '<=', $amount_end];
                            $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                        }
                        $obj = DB::connection("mysql_d1")->table('order_items');
                        $dataArray = $obj->where($where)
                            ->join('users', 'order_items.user_id', '=', 'users.id')
                            ->whereIn('order_items.user_id', $user_ids)
                            ->orderBy('order_items.updated_at', 'desc')
                            ->select(
                                'users.name',
                                'order_items.store_id',
                                'order_items.store_name',
                                'order_items.merchant_name',
                                'order_items.out_trade_no',
                                'order_items.total_amount',
                                'order_items.refund_amount',
                                'order_items.rate',//商户交易时的费率
                                'order_items.fee_amount',
                                'order_items.ways_source_desc',
                                'order_items.pay_status',//系统状态
                                'order_items.pay_status_desc',
                                'order_items.pay_time',
                                'order_items.company',//通道方
                                "order_items.remark"
                            )
                            ->get()->map(function ($value) {
                                return (array)$value;
                            })->toArray();
                    } else {
                        $obj = DB::connection("mysql_d1")->table("orders");
                        if ($pay_status) {
                            $where[] = ['orders.pay_status', '=', $pay_status];
                            $where_desc = $where_desc . ';支付状态：' . $pay_status;
                        }
                        if ($store_id) {
                            $where[] = ['orders.store_id', '=', $store_id];
                            $where_desc = $where_desc . ';门店ID：' . $store_id;
                        }
                        if ($company) {
                            $where[] = ['orders.company', '=', $company];
                            $where_desc = $where_desc . ';通道：' . $company;
                        }
                        if ($ways_source) {
                            $where[] = ['orders.ways_source', '=', $ways_source];
                            $where_desc = $where_desc . ';支付方式：' . $ways_source;
                        }
                        if ($ways_type) {
                            $where[] = ['orders.ways_type', '=', $ways_type];
                            $where_desc = $where_desc . ';支付类型：' . $ways_type;
                        }
                        if ($time_start) {
                            $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                            $where[] = ['orders.created_at', '>=', $time_start];
                            $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                        }
                        if ($time_end) {
                            $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                            $where[] = ['orders.created_at', '<=', $time_end];
                            $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                        }
                        if ($out_trade_no && $out_trade_no != "undefined") {
                            $where[] = ['orders.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($trade_no && $out_trade_no != "undefined") {
                            $where[] = ['orders.trade_no', 'like', '%' . $trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($amount_start) {
                            $where[] = ['orders.total_amount', '>=', $amount_start];
                            $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                        }
                        if ($amount_end) {
                            $where[] = ['orders.total_amount', '<=', $amount_end];
                            $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                        }
                        $dataArray = $obj->where($where)
                            ->join('users', 'orders.user_id', '=', 'users.id')
                            ->whereIn('orders.user_id', $user_ids)
                            ->orderBy('orders.updated_at', 'desc')
                            ->select(
                                'users.name',
                                'orders.store_id',
                                'orders.store_name',
                                'orders.merchant_name',
                                'orders.out_trade_no',
                                'orders.total_amount',
                                'orders.refund_amount',
                                'orders.rate',//商户交易时的费率
                                'orders.fee_amount',
                                'orders.ways_source_desc',
                                'orders.pay_status',//系统状态
                                'orders.pay_status_desc',
                                'orders.pay_time',
                                'orders.company',//通道方
                                "orders.remark"
                            )
                            ->get()->map(function ($value) {
                                return (array)$value;
                            })->toArray();
                    }
                }
            }
        } else {
            if ($is_ct_time) {
                if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                    $obj = DB::table('order_items');
                    if ($pay_status) {
                        $where[] = ['order_items.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = ['order_items.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = ['order_items.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        $where[] = ['order_items.ways_source', '=', $ways_source];
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = ['order_items.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = ['order_items.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = ['order_items.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = ['order_items.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = ['order_items.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = ['order_items.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = ['order_items.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    $dataArray = $obj->where($where)
                        ->join('users', 'order_items.user_id', '=', 'users.id')
                        ->whereIn('order_items.user_id', $user_ids)
                        ->orderBy('order_items.updated_at', 'desc')
                        ->select(
                            'users.name',
                            'order_items.store_id',
                            'order_items.store_name',
                            'order_items.merchant_name',
                            'order_items.out_trade_no',
                            'order_items.total_amount',
                            'order_items.refund_amount',
                            'order_items.rate',//商户交易时的费率
                            'order_items.fee_amount',
                            'order_items.ways_source_desc',
                            'order_items.pay_status',//系统状态
                            'order_items.pay_status_desc',
                            'order_items.pay_time',
                            'order_items.company',//通道方
                            "order_items.remark"
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                } else {
                    if($time_start>="2023-02-01 00:00:00" && $time_end<="2023-02-28 23:59:59"){
                        $obj = DB::table('orders_202302');
                        if ($pay_status) {
                        $where[] = ['orders_202302.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = ['orders_202302.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = ['orders_202302.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        if (in_array($ways_source, ['alipay_face', 'weixin_face'])) {
                            $where[] = ['orders_202302.pay_method', '=', $ways_source];
                        } else {
                            $where[] = ['orders_202302.ways_source', '=', $ways_source];
                        }
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = ['orders_202302.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = ['orders_202302.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = ['orders_202302.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders_202302.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders_202302.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = ['orders_202302.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = ['orders_202302.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    if ($device_id) {
                        $where[] = ['orders_202302.device_id', '=', $device_id];
                        $where_desc = $where_desc . ';设备号：' . $device_id;
                    }
                    $dataArray = $obj->where($where)
                        ->join('users', 'orders_202302.user_id', '=', 'users.id')
                        ->whereIn('orders_202302.user_id', $user_ids)
                        ->orderBy('orders_202302.updated_at', 'desc')
                        ->select(
                            'users.name',
                            'orders_202302.store_id',
                            'orders_202302.store_name',
                            'orders_202302.merchant_name',
                            'orders_202302.out_trade_no',
                            'orders_202302.total_amount',
                            'orders_202302.refund_amount',
                            'orders_202302.rate', //商户交易时的费率
                            'orders_202302.fee_amount',
                            'orders_202302.ways_source_desc',
                            'orders_202302.pay_status', //系统状态
                            'orders_202302.pay_status_desc',
                            'orders_202302.pay_time',
                            'orders_202302.company', //通道方
                            'orders_202302.remark',
                            'orders_202302.device_id'
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                    }else{
                       $obj = DB::table('orders'); 
                       if ($pay_status) {
                        $where[] = ['orders.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = ['orders.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = ['orders.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        if (in_array($ways_source, ['alipay_face', 'weixin_face'])) {
                            $where[] = ['orders.pay_method', '=', $ways_source];
                        } else {
                            $where[] = ['orders.ways_source', '=', $ways_source];
                        }
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = ['orders.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = ['orders.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = ['orders.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = ['orders.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($amount_start) {
                        $where[] = ['orders.total_amount', '>=', $amount_start];
                        $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    }
                    if ($amount_end) {
                        $where[] = ['orders.total_amount', '<=', $amount_end];
                        $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    }
                    if ($device_id) {
                        $where[] = ['orders.device_id', '=', $device_id];
                        $where_desc = $where_desc . ';设备号：' . $device_id;
                    }
                    $dataArray = $obj->where($where)
                        ->join('users', 'orders.user_id', '=', 'users.id')
                        ->whereIn('orders.user_id', $user_ids)
                        ->orderBy('orders.updated_at', 'desc')
                        ->select(
                            'users.name',
                            'orders.store_id',
                            'orders.store_name',
                            'orders.merchant_name',
                            'orders.out_trade_no',
                            'orders.total_amount',
                            'orders.refund_amount',
                            'orders.rate', //商户交易时的费率
                            'orders.fee_amount',
                            'orders.ways_source_desc',
                            'orders.pay_status', //系统状态
                            'orders.pay_status_desc',
                            'orders.pay_time',
                            'orders.company', //通道方
                            'orders.remark',
                            'orders.device_id'
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                    }
                    
                }
            } else {
                if (Schema::hasTable($table)) {
                    // print_r($table);die;
                    $table = 'orders';
                    $obj = DB::table($table);
                    if ($pay_status) {
                        $where[] = [ ''.$table.'.pay_status', '=', $pay_status];
                        $where_desc = $where_desc . ';支付状态：' . $pay_status;
                    }
                    if ($store_id) {
                        $where[] = [ ''.$table.'.store_id', '=', $store_id];
                        $where_desc = $where_desc . ';门店ID：' . $store_id;
                    }
                    if ($company) {
                        $where[] = [ ''.$table.'.company', '=', $company];
                        $where_desc = $where_desc . ';通道：' . $company;
                    }
                    if ($ways_source) {
                        $where[] = [ ''.$table.'.ways_source', '=', $ways_source];
                        $where_desc = $where_desc . ';支付方式：' . $ways_source;
                    }
                    if ($ways_type) {
                        $where[] = [ ''.$table.'.ways_type', '=', $ways_type];
                        $where_desc = $where_desc . ';支付类型：' . $ways_type;
                    }
                    if ($time_start) {
                        $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                        $where[] = [ ''.$table.'.created_at', '>=', $time_start];
                        $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                    }
                    if ($time_end) {
                        $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                        $where[] = [ ''.$table.'.created_at', '<=', $time_end];
                        $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                    }
                    if ($out_trade_no && $out_trade_no != "undefined") {
                        $where[] = [ ''.$table.'.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    if ($trade_no && $out_trade_no != "undefined") {
                        $where[] = [ ''.$table.'.trade_no', 'like', '%' . $trade_no . '%'];
                        $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                    }
                    // print_r($amount_start);die;
                    // if ($amount_start) {
                    //     $where[] = [''.$table.'.total_amount', '>=', $amount_start];
                    //     $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                    // }
                    // if ($amount_end) {
                    //     $where[] = [''.$table.'.total_amount', '<=', $amount_end];
                    //     $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                    // }
                    // print_r($where);die;
                    $dataArray = $obj->where($where)
                        ->join('users',   ''.$table.'.user_id', '=', 'users.id')
                        ->whereIn(  ''.$table.'.user_id', $user_ids)
                        ->orderBy(  ''.$table.'.updated_at', 'desc')
                        ->select(
                            'users.name',
                            ''.$table.'.store_id',
                            ''.$table.'.store_name',
                            ''.$table.'.merchant_name',
                            ''.$table.'.out_trade_no',
                            ''.$table.'.total_amount',
                            ''.$table.'.refund_amount',
                            ''.$table.'.rate',//商户交易时的费率
                            ''.$table.'.fee_amount',
                            ''.$table.'.ways_source_desc',
                            ''.$table.'.pay_status',//系统状态
                            ''.$table.'.pay_status_desc',
                            ''.$table.'.pay_time',
                            ''.$table.'.company',//通道方
                            ''.$table.'.remark'//
                        )
                        ->get()->map(function ($value) {
                            return (array)$value;
                        })->toArray();
                } else {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                        if ($pay_status) {
                            $where[] = ['order_items.pay_status', '=', $pay_status];
                            $where_desc = $where_desc . ';支付状态：' . $pay_status;
                        }
                        if ($store_id) {
                            $where[] = ['order_items.store_id', '=', $store_id];
                            $where_desc = $where_desc . ';门店ID：' . $store_id;
                        }
                        if ($company) {
                            $where[] = ['order_items.company', '=', $company];
                            $where_desc = $where_desc . ';通道：' . $company;
                        }
                        if ($ways_source) {
                            $where[] = ['order_items.ways_source', '=', $ways_source];
                            $where_desc = $where_desc . ';支付方式：' . $ways_source;
                        }
                        if ($ways_type) {
                            $where[] = ['order_items.ways_type', '=', $ways_type];
                            $where_desc = $where_desc . ';支付类型：' . $ways_type;
                        }
                        if ($time_start) {
                            $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                            $where[] = ['order_items.created_at', '>=', $time_start];
                            $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                        }
                        if ($time_end) {
                            $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                            $where[] = ['order_items.created_at', '<=', $time_end];
                            $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                        }
                        if ($out_trade_no && $out_trade_no != "undefined") {
                            $where[] = ['order_items.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($trade_no && $out_trade_no != "undefined") {
                            $where[] = ['order_items.trade_no', 'like', '%' . $trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($amount_start) {
                            $where[] = ['order_items.total_amount', '>=', $amount_start];
                            $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                        }
                        if ($amount_end) {
                            $where[] = ['order_items.total_amount', '<=', $amount_end];
                            $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                        }
                        $dataArray = $obj->where($where)
                            ->join('users', 'order_items.user_id', '=', 'users.id')
                            ->whereIn('order_items.user_id', $user_ids)
                            ->orderBy('order_items.updated_at', 'desc')
                            ->select(
                                'users.name',
                                'order_items.store_id',
                                'order_items.store_name',
                                'order_items.merchant_name',
                                'order_items.out_trade_no',
                                'order_items.total_amount',
                                'order_items.refund_amount',
                                'order_items.rate',//商户交易时的费率
                                'order_items.fee_amount',
                                'order_items.ways_source_desc',
                                'order_items.pay_status',//系统状态
                                'order_items.pay_status_desc',
                                'order_items.pay_time',
                                'order_items.company',//通道方
                                "order_items.remark"
                            )
                            ->get()->map(function ($value) {
                                return (array)$value;
                            })->toArray();
                    } else {
                        $obj = DB::table('orders');
                        if ($pay_status) {
                            $where[] = ['orders.pay_status', '=', $pay_status];
                            $where_desc = $where_desc . ';支付状态：' . $pay_status;
                        }
                        if ($store_id) {
                            $where[] = ['orders.store_id', '=', $store_id];
                            $where_desc = $where_desc . ';门店ID：' . $store_id;
                        }
                        if ($company) {
                            $where[] = ['orders.company', '=', $company];
                            $where_desc = $where_desc . ';通道：' . $company;
                        }
                        if ($ways_source) {
                            if (in_array($ways_source, ['alipay_face', 'weixin_face'])) {
                                $where[] = ['orders.pay_method', '=', $ways_source];
                            } else {
                                $where[] = ['orders.ways_source', '=', $ways_source];
                            }
                            $where_desc = $where_desc . ';支付方式：' . $ways_source;
                        }
                        if ($ways_type) {
                            $where[] = ['orders.ways_type', '=', $ways_type];
                            $where_desc = $where_desc . ';支付类型：' . $ways_type;
                        }
                        if ($time_start) {
                            $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                            $where[] = ['orders.created_at', '>=', $time_start];
                            $where_desc = $where_desc . ';订单开始时间：' . $time_start;
                        }
                        if ($time_end) {
                            $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                            $where[] = ['orders.created_at', '<=', $time_end];
                            $where_desc = $where_desc . ';订单结束时间：' . $time_end;
                        }
                        if ($out_trade_no && $out_trade_no != "undefined") {
                            $where[] = ['orders.out_trade_no', 'like', '%' . $out_trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($trade_no && $out_trade_no != "undefined") {
                            $where[] = ['orders.trade_no', 'like', '%' . $trade_no . '%'];
                            $where_desc = $where_desc . ';订单编号：' . $out_trade_no;
                        }
                        if ($amount_start) {
                            $where[] = ['orders.total_amount', '>=', $amount_start];
                            $where_desc = $where_desc . ';订单金额大于等于：' . $amount_start;
                        }
                        if ($amount_end) {
                            $where[] = ['orders.total_amount', '<=', $amount_end];
                            $where_desc = $where_desc . ';订单金额小于等于：' . $amount_end;
                        }
                        if ($device_id) {
                            $where[] = ['orders.device_id', '=', $device_id];
                            $where_desc = $where_desc . ';设备号：' . $device_id;
                        }
                        $dataArray = $obj->where($where)
                            ->join('users', 'orders.user_id', '=', 'users.id')
                            ->whereIn('orders.user_id', $user_ids)
                            ->orderBy('orders.updated_at', 'desc')
                            ->select(
                                'users.name',
                                'orders.store_id',
                                'orders.store_name',
                                'orders.merchant_name',
                                'orders.out_trade_no',
                                'orders.total_amount',
                                'orders.refund_amount',
                                'orders.rate',//商户交易时的费率
                                'orders.fee_amount',
                                'orders.ways_source_desc',
                                'orders.pay_status',//系统状态
                                'orders.pay_status_desc',
                                'orders.pay_time',
                                'orders.company',//通道方
                                'orders.remark',
                                'orders.device_id'
                            )
                            ->get()->map(function ($value) {
                                return (array)$value;
                            })->toArray();
                    }
                }
            }
        }

        foreach ($dataArray as $k=>$v){
            $dataArray[$k]['refund_time'] = $this->refundTime($v['out_trade_no']);
        }

        $filename = '订单导出.csv';
        $s_array = ['筛选条件：' . $where_desc];
        $tileArray = ['代理商ID', '门店ID', '门店名称', '收银员', '订单号', '订单金额', '退款金额', '费率', '手续费', '支付方式', '支付状态', '支付状态说明', '付款时间', '通道', '备注', '设备号', '退款时间'];

        return $this->exportToExcel($filename, $s_array, $tileArray, $dataArray);
    }
    
    //渠道通道导出
    public function UserCompanyExcelDown(Request $request){
        $user = $this->parseToken(); //用户信息
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        //获取传递的参数
        $company_id = $request->get('company_id', ''); // 排序：1-交易笔数,由大到小;2-交易笔数由小到大;3-交易金额由大到小;4-交易金额由小到大
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');
        $sub_user_id = $request->get('user_id', '');
        if(empty($sub_user_id)){
            $sub_user_id=$user_id;
        }
        
        if(empty($time_start)){
            $time_start=date('Y-m-d',time());
        }
        if(empty($time_end)){
            $time_end=date('Y-m-d',time());
        }
        if ($time_start != $time_end) {
            $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
            if (!$date) {
                return json_encode([
                    'status' => 2,
                    'message' => '开始时间不能超过结束时间'
                ]);
            }
        }
        // //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }

        $user_ids = $this->getSubIds($sub_user_id);
        $where[] = ['settling_day', '>=', $time_start];
        $where[] = ['settling_day', '<=', $time_end];
        $store = DB::table('stores')->where('pid', '=', 0)->whereIn('user_id', $user_ids)->select('id','store_id', 'store_name')->get(); // 门店列
        $array=array();
        foreach($store as $k=>$v){
            $p_stores = DB::table('stores')->where('pid', $v->id)->select('store_id')->get(); // 查找总店下的分店
            if(!empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $v->store_id;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $store_ids[] = $v1['store_id'];
                }
            }else{
                $store_ids[0] = $v->store_id;
            }
            if(empty($company_id)){
                $way=DB::table('store_pay_ways')->whereIn('store_id',$store_ids)->select('company')->distinct()->get();
                foreach($way as $key=>$val){
                    $company_ways=DB::table('store_ways_desc')->where('company', $val->company)->select('ways_type as receive_code')->get();
                    $company_ways=json_decode($company_ways,true);
                    
                    $table='wft_stores_orders_' . date('Ym', strtotime($time_start)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($time_end)) . '_bill';
                    
                    $ways_amount=DB::connection('old_mysql')->table($table)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $total_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $total_amount += $obj->order_amount;
                    }
                    $total_amount=$total_amount/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount += $obj->refund_amount;
                    }
                    $refund_amount=$refund_amount/100;
                    
                    $company_config=DB::table('company_config')->whereIn('store_id', $store_ids)->where('company', $val->company)->first();
                    if(empty($company_config)){
                        $store_rate='无此通道';
                    }else{
                        $store_rate=$company_config->configure_channel_fee;
                    }
                    if(!empty($company_config->users_rate)){
                        $user_rate1=unserialize($company_config->users_rate);
                        if(!empty($user_rate1[1]['agent_id'])){
                            $sub_user_id=$user_rate1[1]['agent_id'];
                        }
                    }
                    $user_rate=DB::table('user_rates')->where('user_id', $sub_user_id)->where('company', $val->company)->first();
                    if(empty($user_rate)){
                        $user_rates='无此成本';
                    }else{
                        if($company_config->model==1){
                            $user_rates=$user_rate->server_rate;
                        }else if($company_config->model==2){
                            $user_rates=$user_rate->era_rate;
                        }else if($company_config->model==3){
                            $user_rates=$user_rate->rate;
                        }else if($company_config->model==4){
                            $user_rates=$user_rate->yu_rate;
                        }else{
                            $user_rates=$user_rate->rate;
                        }
                    }
                    // dump($v);die;
                    $company_name = '';
                    if( $val->company == 'vbill' ){
                        $company_name = DB::table('vbill_stores')->where([ 'store_id' => $v->store_id ])->value('mno') . "\t";
                    }else if( $val->company == 'wftpay' ){
                        $company_name = DB::table('wftpay_stores')->where([ 'store_id' => $v->store_id ])->value('mch_id') . "\t";
                    }else if( $val->company == 'hwcpay' ){
                        $company_name = DB::table('hwcpay_stores')->where([ 'store_id' => $v->store_id ])->value('merchant_num') . "\t";
                    }else if( $val->company == 'nongjin' ){
                        $company_name = DB::table('nongjin_stores')->where([ 'store_id' => $v->store_id ])->value('merchantNo') . "\t";
                    }else if( $val->company == 'abc' ){
                        $company_name = DB::table('abc_stores')->where([ 'store_id' => $v->store_id ])->value('MerchantId') . "\t";
                    }else if( $val->company == 'wingpay' ){
                        $company_name = DB::table('wing_stores')->where([ 'store_id' => $v->store_id ])->value('merchantNo') . "\t";
                    }else if( $val->company == 'pingan' ){
                        $company_name = DB::table('pingan_stores')->where([ 'store_id' => $v->store_id ])->value('merchant_id') . "\t";
                    }else if( $val->company == 'lianfu' ){
                        $company_name = DB::table('lianfu_stores')->where([ 'store_id' => $v->store_id ])->value('apikey') . "\t";
                    }else if( $val->company == 'lianfuyoupay' ){
                        $company_name = DB::table('lianfuyoupay_stores')->where([ 'store_id' => $v->store_id ])->value('apikey') . "\t";
                    }else{
                        $company_name='其他';
                    }
                    $store=DB::table('stores')->where('store_id', $v->store_id)->first();
                    $user=DB::table('users')->where('id', $store->user_id)->first();
                    // $company_config=DB::table('users')->where('store_id', $v->store_id)->where('company', $val->company)->first();
                    $item=array('name' => $user->name,'store_id'=>$v->store_id . "\t",'store_name'=>$v->store_name,'company'=> $this->get_commany_name( $val->company ) , 'rate' => $user_rates,'store_rate' => $store_rate, 'company_name' => $company_name,'total_amount'=>$total_amount,'refund_amount'=>$refund_amount);
                    $array[]=$item;
                }
            }else{
                $company_ways=DB::table('store_ways_desc')->where('company', $company_id)->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                
                $table='wft_stores_orders_' . date('Ym', strtotime($time_start)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($time_end)) . '_bill';
                
                $ways_amount=DB::connection('old_mysql')->table($table)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $total_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $total_amount += $obj->order_amount;
                }
                $total_amount=$total_amount/100;
                
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount1=DB::connection('old_mysql')->table($table1)->whereIn('shop_id', $store_ids)->whereIn('receive_code', $company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                $refund_amount_zong->unionAll($refund_amount1);
                $refund_amount=0;
                foreach ($refund_amount_zong->get() as $obj) {
                    $refund_amount += $obj->refund_amount;
                }
                $refund_amount=$refund_amount/100;
                
                $company_config=DB::table('company_config')->whereIn('store_id', $store_ids)->where('company', $company_id)->first();
                if(empty($company_config)){
                    $store_rate='无此通道';
                }else{
                    $store_rate=$company_config->configure_channel_fee;
                }
                if(!empty($company_config->users_rate)){
                    $user_rate1=unserialize($company_config->users_rate);
                    if(!empty($user_rate1[1]['agent_id'])){
                        $agent_id=$user_rate1[1]['agent_id'];
                        $user_rate=DB::table('user_rates')->where('user_id', $agent_id)->where('company', $company_id)->first();
                    }
                }
                if(empty($user_rate)){
                    $user_rates='无成本';
                }else{
                    if(empty($company_config)){
                        $user_rates='无此通道';
                    }else{
                        if($company_config->model==1){
                            $user_rates=$user_rate->server_rate;
                        }else if($company_config->model==2){
                            $user_rates=$user_rate->era_rate;
                        }else if($company_config->model==3){
                            $user_rates=$user_rate->rate;
                        }else if($company_config->model==4){
                            $user_rates=$user_rate->yu_rate;
                        }else{
                            $user_rates=$user_rate->rate;
                        }
                    }
                }
                
                if( $company_id == 'vbill' ){
                        $company_name = DB::table('vbill_stores')->where([ 'store_id' => $v->store_id ])->value('mno') . "\t";
                    }else if( $company_id == 'wftpay' ){
                        $company_name = DB::table('wftpay_stores')->where([ 'store_id' => $v->store_id ])->value('mch_id') . "\t";
                    }else if( $company_id == 'hwcpay' ){
                        $company_name = DB::table('hwcpay_stores')->where([ 'store_id' => $v->store_id ])->value('merchant_num') . "\t";
                    }else if( $company_id == 'nongjin' ){
                        $company_name = DB::table('nongjin_stores')->where([ 'store_id' => $v->store_id ])->value('merchantNo') . "\t";
                    }else if( $company_id == 'abc' ){
                        $company_name = DB::table('abc_stores')->where([ 'store_id' => $v->store_id ])->value('MerchantId') . "\t";
                    }else if( $company_id == 'wingpay' ){
                        $company_name = DB::table('wing_stores')->where([ 'store_id' => $v->store_id ])->value('merchantNo') . "\t";
                    }else if( $company_id == 'pingan' ){
                        $company_name = DB::table('pingan_stores')->where([ 'store_id' => $v->store_id ])->value('merchant_id') . "\t";
                    }else if( $company_id == 'lianfu' ){
                        $company_name = DB::table('lianfu_stores')->where([ 'store_id' => $v->store_id ])->value('apikey') . "\t";
                    }else if( $company_id == 'lianfuyoupay'){
                        $company_name = DB::table('lianfuyoupay_stores')->where([ 'store_id' => $v->store_id ])->value('apikey') . "\t";
                    }else{
                        $company_name='其他';
                    }
                $store=DB::table('stores')->where('store_id', $v->store_id)->first();
                $user=DB::table('users')->where('id', $store->user_id)->first();
                
                $item = array( 'name' => $user->name,'store_id' => $v->store_id . "\t", 'store_name' => $v->store_name, 'company' => $company_id, 'rate' => $user_rates,'store_rate' => $store_rate, 'company_name' => $company_name, 'total_amount' => $total_amount , 'refund_amount' => $refund_amount );
                $array[]=$item;
            }
            unset($store_ids);
        }
        // dump($array);die;
        $filename = '渠道通道表格.csv';
        $s_array = ['筛选条件：' . '暂不导出'];
        $tileArray = ['代理名称','门店ID', '门店名称','通道','渠道成本费率','商户费率', '商户号','交易总金额','退款总额'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));

        fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($array as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }


    public function exportToExcel($filename, $s_array, $tileArray = [], $dataArray = [])
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($dataArray as $item) {
            $item['rate'] = $item['rate'] / 100;
            if(!empty($item['out_trade_no'])){
                $item['out_trade_no'] = $item['out_trade_no']. "\t";
            }
            if(!empty($item['store_id'])){
                $item['store_id'] = $item['store_id']. "\t";
            }
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }

    //采蝶轩
    private function ZENExcelDown(Request $request, $merchant_id)
    {
        try {
            $storeId = $request->get('store_id', '');
            $merchantId = $request->get('merchant_id', '');
            $startDate = $request->get('time_start', '');
            $endDate = $request->get('time_end', '');

            $storeList = DB::table('merchant_stores')->join('stores', 'merchant_stores.store_id', '=', 'stores.store_id', 'inner')
                ->where('merchant_stores.merchant_id', $merchant_id)
                ->pluck('stores.store_name', 'stores.store_id');
            $storeList = $storeList->toArray();
            if (!$storeList) {
                throw new \Exception("未查找到门店信息");
            }
            $storeIds = array_keys($storeList);
            if ($storeId) {
                if (!in_array($storeId, $storeIds)) {
                    throw new \Exception("你没有该门店的权限");
                }
                $storeIds = [$storeId];
            }


            $years = date('Y', strtotime($endDate)) - date('Y', strtotime($startDate));
            $MonthTotal = $years * 12 + date('m', strtotime($endDate)) - date('m', strtotime($startDate));

            $tableName = 'wft_stores_orders_' . date('Ym', strtotime($startDate)) . '_bill';
            $tableName = 'wft_stores_orders_cakeking_bill';
            $query = DB::connection('old_mysql')->table($tableName)
                ->where(function ($q) use ($storeIds, $merchantId) {
                    $q->whereIn('shop_id', $storeIds);
                    if ($merchantId > 0) {
                        $q->where('merchant_id', $merchantId);
                    }
                    return $q;
                })
                ->whereBetween('bill_date', [strtotime($startDate), strtotime($endDate)])
                ->select([
                    DB::raw("sum(order_total) as order_total"),
                    DB::raw("sum(order_amount) as order_amount"),
                    DB::raw("sum(refund_total) as refund_total"),
                    DB::raw("sum(refund_amount) as refund_amount"),
                    DB::raw("sum(receive_fee) as receive_fee"),
                    DB::raw("sum(receive_refund_fee) as receive_refund_fee"),
                    DB::raw('FROM_UNIXTIME(bill_date, "%Y-%m-%d") as bill_date'),
                ])
                ->groupBy(DB::raw('CONCAT(FROM_UNIXTIME(bill_date, "%Y-%m-%d"))'));
            for ($i = 0; $i < $MonthTotal; $i++) {
                $num = $i + 1;
                $numTime = strtotime("+" . $num . " month", strtotime($startDate));
                $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                $union = DB::connection('old_mysql')->table($tableName)
                    ->where(function ($q) use ($storeIds, $merchantId) {
                        $q->whereIn('shop_id', $storeIds);
                        if ($merchantId > 0) {
                            $q->where('merchant_id', $merchantId);
                        }
                        return $q;
                    })
                    ->whereBetween('bill_date', [strtotime($startDate), strtotime($endDate)])
                    ->select([
                        DB::raw("sum(order_total) as order_total"),
                        DB::raw("sum(order_amount) as order_amount"),
                        DB::raw("sum(refund_total) as refund_total"),
                        DB::raw("sum(refund_amount) as refund_amount"),
                        DB::raw("sum(receive_fee) as receive_fee"),
                        DB::raw("sum(receive_refund_fee) as receive_refund_fee"),
                        DB::raw('FROM_UNIXTIME(bill_date, "%Y-%m-%d") as bill_date'),
                    ])
                    ->groupBy(DB::raw('CONCAT(FROM_UNIXTIME(bill_date, "%Y-%m-%d"))'));
                $query = $query->unionAll($union);
            }

            ini_set('memory_limit', '512M');
            ini_set('max_execution_time', 0);
            ob_end_clean();
            ob_start();
            header("Content-Type: text/csv");
            header("Content-Disposition:filename=" . "对账统计.csv");
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
            fputcsv($fp, []);
            fputcsv($fp, [
                '商户号',
                '商户名称',
                '结算日期',
                '开始时间',
                '结束时间',
                '收单订单总笔数',
                '退单订单总笔数',
                '应收本金',
                '手续费',
                '应退本金',
                '应退手续费',
                '实收',
                '实收净额',
            ]);
            $query->get()->each(function ($_obj) use ($storeList, $fp) {
                $netAmount = $_obj->order_amount - $_obj->receive_fee - $_obj->refund_amount + $_obj->receive_refund_fee;
                fputcsv($fp, [
                    '45436105462C030',
                    '合肥采蝶轩企业管理服务有限公司',
                    date('Y-m-d', strtotime('+1 day', strtotime($_obj->bill_date))),
                    $_obj->bill_date,
                    $_obj->bill_date,
                    $_obj->order_total,
                    $_obj->refund_total,
                    bcdiv($_obj->order_amount, 100, 2),
                    bcdiv($_obj->receive_fee, 100, 2),
                    bcdiv($_obj->refund_amount, 100, 2),
                    bcdiv($_obj->receive_refund_fee, 100, 2),
                    bcdiv($_obj->order_amount-$_obj->refund_amount, 100, 2),
                    bcdiv($netAmount, 100, 2),
                ]);
            });
            ob_flush();
            flush();
            ob_end_clean();
        } catch (\Exception $e) {
            echo "未查找数据";
        }
    }

    //商户对账统计导出
    public function MerchantOrderCountExcelDown(Request $request)
    {
        $merchant = $this->parseToken();
        
        //采蝶轩
        if ($merchant->phone=='19810980859'){
            $this->ZENExcelDown($request,$merchant->merchant_id);
            die();
            // return false;
        }
        
        $store_id = $request->get('store_id', '');
        $merchant_id = $request->get('merchant_id', '');
        $time_start_s = date('Y-m-d 00:00:00', time());
        $time_start_e = date('Y-m-d 23:59:59', time());

        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');

        if (in_array($time_start,[null,''])){
            $time_start=$time_start_s;
        }

        if (in_array($time_end,[null,''])){
            $time_end=$time_start_e;
        }
        $count_data = $request->get('count_data', '');
        $where_desc = '';
        $store_name = "全部门店";

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 2;
        $now_time = date('Y-m-d H:i:s', time());
        $end = date('Y-m-d 22:00:00', time());
        if ($now_time > $end) {
            $day = 31;
        }

        if ($date > $day) {
            echo '时间筛选不能超过' . $day . '天';
        }

        //跨天操作
        $time_start_db = date('Ymd', strtotime($time_start));
        $time_end_db = date('Ymd', strtotime($time_end));;
        $is_ct_time=0;
        if ($time_start_db != $time_end_db) {
            $is_ct_time=1;
        }

        $MerchantOrderExcelDown = Cache::get('ExcelDown');
        if ($MerchantOrderExcelDown) {
            echo '正在生成数据请1分钟后再来操作';
            die;
        } else {
            Cache::put('ExcelDown', '1', 1);
        }

        if ($store_id) {
            $store = Store::where('store_id', $store_id)
                ->select('store_short_name')
                ->first();

            if ($store) {
                $store_name = $store->store_short_name;
            }
        }

        $count_data = json_decode($count_data, true);

        $filename = '订单导出.csv';
        $tileArray = [
            '时间',
            '门店名称',
            '支付渠道',
            '交易金额',
            '交易笔数',
            '商家实收',
            '实际净额',
            '结算服务费/手续费',
            '退款金额',
            '退款笔数'

        ];
        $data = [
            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '支付宝',
                'total_amount' => $count_data['alipay_total_amount'],
                'total_count' => $count_data['alipay_total_count'],
                'alipay_get_amount' => $count_data['alipay_get_amount'],
                'receipt_amount' => $count_data['alipay_receipt_amount'],
                'fee_amount' => $count_data['alipay_fee_amount'],
                'refund_amount' => $count_data['alipay_refund_amount'],
                'refund_count' => $count_data['alipay_refund_count'],
            ],
            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '微信支付',
                'total_amount' => $count_data['weixin_total_amount'],
                'total_count' => $count_data['weixin_total_count'],
                'alipay_get_amount' => $count_data['weixin_get_amount'],
                'receipt_amount' => $count_data['weixin_receipt_amount'],
                'fee_amount' => $count_data['weixin_fee_amount'],
                'refund_amount' => $count_data['weixin_refund_amount'],
                'refund_count' => $count_data['weixin_refund_count'],
            ],
            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '京东',
                'total_amount' => $count_data['jd_total_amount'],
                'total_count' => $count_data['jd_total_count'],
                'alipay_get_amount' => $count_data['jd_get_amount'],
                'receipt_amount' => $count_data['jd_receipt_amount'],
                'fee_amount' => $count_data['jd_fee_amount'],
                'refund_amount' => $count_data['jd_refund_amount'],
                'refund_count' => $count_data['jd_refund_count'],
            ],
            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '刷卡',
                'total_amount' => $count_data['un_total_amount'],
                'total_count' => $count_data['un_total_count'],
                'alipay_get_amount' => $count_data['un_get_amount'],
                'receipt_amount' => $count_data['un_receipt_amount'],
                'fee_amount' => $count_data['un_fee_amount'],
                'refund_amount' => $count_data['un_refund_amount'],
                'refund_count' => $count_data['un_refund_count'],
            ],
            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '云闪付',
                'total_amount' => $count_data['unqr_total_amount'],
                'total_count' => $count_data['unqr_total_count'],
                'alipay_get_amount' => $count_data['unqr_get_amount'],
                'receipt_amount' => $count_data['unqr_receipt_amount'],
                'fee_amount' => $count_data['unqr_fee_amount'],
                'refund_amount' => $count_data['unqr_refund_amount'],
                'refund_count' => $count_data['unqr_refund_count'],
            ],

            [
                'time' => $time_start . '-' . $time_end,
                'store_name' => $store_name,
                'ways_type' => '总计',
                'total_amount' => $count_data['total_amount'],
                'total_count' => $count_data['total_count'],
                'alipay_get_amount' => $count_data['get_amount'],
                'receipt_amount' => $count_data['receipt_amount'],
                'fee_amount' => $count_data['fee_amount'],
                'refund_amount' => $count_data['refund_amount'],
                'refund_count' => $count_data['refund_count'],
            ],
        ];
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($data as $item) {
            $index++;
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
        ob_end_clean();
    }


    //服务商-分润账单导出
    public function CommissionExcelDown(Request $request)
    {
        $time = $request->get('time_start', ''); //交易时间，年-月
        $user_id = $request->get('user_id', '');  //服务商id
        $amount_start = $request->get('amount_start', ''); //开始金额
        $amount_end = $request->get('amount_end', ''); //结束金额

        $token = $this->parseToken();
        $token_user_id = $token->user_id;

        $MerchantOrderExcelDown = Cache::get('ExcelDown_fr');
        if ($MerchantOrderExcelDown) {
            echo '正在生成数据请2分钟后再来操作';
            die;
        } else {
            Cache::put('ExcelDown_fr', '1', 2);
        }

        $re_data = [
            'time_start' => $time,
            'user_id' => $user_id
        ];
        $check_data = [
            'time_start' => '交易时间',
            'user_id' => '代理商名称'
        ];
        $check = $this->check_required($re_data, $check_data);
        if ($check) {
            $this->status = '2';
            $this->message = $check;
            return $this->format();
        }

        $time_arr = explode('-', $time);
        $year = $time_arr[0];
        $month = $time_arr[1];
        if (!isset($year) || empty($year) || !isset($month) || empty($month)) {
            $this->status = '2';
            $this->message = '时间格式不正确';
            return $this->format();
        }
        $month_day = date('t', strtotime($time));
        $start_time = date('Y-m-d H:i:s', mktime(0, 0, 0, $month, 1, $year));
        $end_time = date('Y-m-d H:i:s', mktime(23, 59, 59, $month, $month_day, $year));

        //限制时间
//        $now_time = date('Y-m-d H:i:s', time());
//        $true_time = date('Y-m-d 22:00:00', time());
//        if ($now_time < $true_time){
//            echo '请在22:00:00以后导出';
//            die;
//        }

        $where = [];
        $where_desc = '';
        if ($amount_start) {
            $where[] = ['o.total_amount', '>=', "$amount_start"];
            $where_desc = '交易开始金额: '.$amount_start;
        }

        if ($amount_end) {
            $where[] = ['o.total_amount', '<=', "$amount_end"];
            $where_desc = $where_desc.' 交易结束金额: '.$amount_end;
        }

        if (isset($user_id) && ($user_id != 'undefined') && $user_id) {
            $user_ids = $this->getSubIds($user_id);

            $user_info = DB::table('users')->where('id', $user_id)
                ->where('is_delete', '0')
                ->first();
            if ($user_info) {
                $where_desc = $where_desc.' 服务商: '.$user_info->name;
            }
        } else {
            $user_ids = $this->getSubIds($token_user_id);
        }

        $where_desc = $where_desc.' 交易开始时间: '.$start_time;
        $where_desc = $where_desc.' 交易结束时间: '.$end_time;

        $filter_array = ['筛选条件：' . $where_desc];

        $obj = DB::table('orders as o')->select([
            DB::raw("date_format(o.pay_time, '%Y-%m-%d') AS `modify_pay_time`"),
            'o.store_name',
            'o.company',
            'o.rate',
            DB::raw("u.rate AS `cost_rate`"),  //成本费率
            'o.ways_source_desc',
            DB::raw("SUM(`o`.`total_amount`) AS `total_amount`"), //交易金额
            DB::raw("SUM(`o`.`refund_amount`) AS `total_refund_amount`"), //退款交易金额
            DB::raw("SUM(`o`.`mdiscount_amount`) AS `mdiscount_amount_sum`"), //商家优惠金额
            'o.pay_status',
            'o.pay_status_desc',
            DB::raw("COUNT(`o`.`total_amount`) as `count_order`")
        ])
            ->leftjoin('user_rates as u', function ($join) use ($user_id) {
                $join->on('u.ways_type', '=', 'o.ways_type')
                    ->where('u.user_id', '=', $user_id);
            })
            ->where($where)
            ->where('o.pay_time', '>=', "$start_time")
            ->where('o.pay_time', '<=', "$end_time")
            ->where('o.ways_type', '<>', '18888') //会员卡支付
            ->where('o.ways_type', '<>', '2005')
            ->where('o.company', '<>', 'alipay')
            ->where('o.company', '<>', 'weixin')
            ->whereNotNull('o.total_amount')
            ->whereIn('o.pay_status', ['1', '6'])
            ->whereIn('o.user_id', $user_ids)
            ->groupBy(['modify_pay_time', 'o.store_id', 'o.company', 'o.rate', 'o.ways_source', 'o.pay_status'])
            ->orderBy('modify_pay_time', 'asc');

        if (isset($user_info) && $user_info) {
            $filename = $time.'-'.$user_info->name.'-'.$user_info->level_name.'-分润账单.csv';
        } else {
            $filename = $time.'-分润账单.csv';
        }
        $tileArray = [
            '交易时间',
            '商户名称',
            '交易渠道',
            '费率(%)',
            '成本费率(%)',
            '支付类型',
            '交易金额',
            '商家优惠金额',
            '支付状态',
            '支付状态描述',
            '交易笔数'
        ];

        $data = $obj->get()->toArray();
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
        fputcsv($fp, $filter_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($data as $item) {
            $item = get_object_vars($item);

            switch ($item['company']) {
                case 'mybank': $item['company'] = '快钱支付'; break;
                case 'herongtong': $item['company'] = '和融通'; break;
                case 'newland': $item['company'] = '新大陆'; break;
                case 'vbill': $item['company'] = '随行付'; break;
                case 'dlb': $item['company'] = '哆啦宝'; break;
                case 'tfpay': $item['company'] = 'TF通道'; break;
                case 'zft': $item['company'] = '花呗'; break;
                case 'fuiou': $item['company'] = '富友'; break;
                case 'alipay': $item['company'] = '支付宝官方'; break;
                case 'weixin': $item['company'] = '微信官方'; break;
                case 'jdjr': $item['company'] = '京东聚合'; break;
                case 'hkrt': $item['company'] = '海科融通'; break;
                case 'ltf': $item['company'] = '联拓付'; break;
                case 'easypay': $item['company'] = '易生支付'; break;
                case 'hulu': $item['company'] = '葫芦天下'; break;
                case 'linkage': $item['company'] = '联动优势'; break;
                case 'huipay': $item['company'] = '汇付'; break;
                case 'lianfu': $item['company'] = '工行'; break;
                case 'changsha': $item['company'] = '长沙银行'; break;
                case 'lianfuyouzheng': $item['company'] = '邮政'; break;
            }

            if ($item['pay_status'] == '6') {
                $item['total_amount'] = $item['total_refund_amount'];
                unset($item['total_refund_amount']);
            } else {
                unset($item['total_refund_amount']);
            }

            $index++;
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
        ob_end_clean();
    }


    //服务商-sfkj-分润账单导出
    public function SFKJCommissionExcelDown(Request $request)
    {
        $time = $request->get('time_start', '');
        $user_id = $request->get('user_id', '');  //服务商id
        $amount_start = $request->get('amount_start', '');
        $amount_end = $request->get('amount_end', '');

        $token = $this->parseToken();
        $token_user_id = $token->user_id;

        $MerchantOrderExcelDown = Cache::get('ExcelDown_sfkj');
        if ($MerchantOrderExcelDown) {
            echo '正在生成数据请2分钟后再来操作';
            die;
        } else {
            Cache::put('ExcelDown_sfkj', '1', 2);
        }

        if (env('DB_DATABASE_FIRSTPAY')) {
            $db = DB::connection('mysql_firstpay'); //连接首付科技数据库
        } else {
            $this->status = '3';
            $this->message = '首付科技数据库连接异常';
            return $this->format();
        }

        $re_data = [
            'time_start' => $time,
        ];
        $check_data = [
            'time_start' => '交易时间',
        ];
        $check = $this->check_required($re_data, $check_data);
        if ($check) {
            $this->status = '2';
            $this->message = $check;
            return $this->format();
        }

        $time_arr = explode('-', $time);
        $year = $time_arr[0];
        $month = $time_arr[1];
        if (!isset($year) || empty($year) || !isset($month) || empty($month)) {
            $this->status = '2';
            $this->message = '时间格式不正确';
            return $this->format();
        }
        $month_day = date('t', strtotime($time));
        $start_time = date('Y-m-d H:i:s', mktime(0,0,0,$month,1,$year));
        $end_time = date('Y-m-d H:i:s', mktime(23,59,59,$month,$month_day,$year));

        //限制时间
//        $now_time = date('Y-m-d H:i:s', time());
//        $true_time = date('Y-m-d 22:00:00', time());
//        if ($now_time < $true_time){
//            echo '请在22:00:00以后导出';
//            die;
//        }

        $where = [];
        $where_desc = '';
        if ($amount_start) {
            $where[] = ['total_amount', '>=', "$amount_start"];
            $where_desc = '交易开始金额: '.$amount_start;
        }
        if ($amount_end) {
            $where[] = ['total_amount', '<=', "$amount_end"];
            $where_desc = $where_desc.' 交易结束金额: '.$amount_end;
        }
        if (isset($user_id) && ($user_id != 'undefined') && $user_id) {
            $user_ids = $this->getSubIds($user_id);

            $user_info = $db->table('users')->where('id', $user_id)
                ->where('is_delete', '0')
                ->first();
            if ($user_info) {
                $where_desc = $where_desc.' 服务商: '.$user_info->name;
            }
        } else {
            $user_ids = $this->getSubIds($token_user_id);
        }
        if (1) {
            $where[] = ['ways_type', '!=', '2005'];
        }
        $where_desc = $where_desc.' 交易开始时间: '.$start_time;
        $where_desc = $where_desc.' 交易结束时间: '.$end_time;

        $filter_array = ['筛选条件：' . $where_desc];

        $obj = $db->table('orders')->select([
            DB::raw("date_format(pay_time, '%Y-%m-%d') AS `modify_pay_time`"),
            'store_name',
            'company',
            'rate',
            'cost_rate',  //成本费率
            'ways_source_desc',
            DB::raw("SUM(`total_amount`) AS `total_amount_sum`"),
            DB::raw("SUM(`mdiscount_amount`) AS `mdiscount_amount_sum`"),
            DB::raw("SUM(IF((`pay_status`=1), `total_amount`, 0)) as `total_success_amount`"),
            DB::raw("SUM(IF((`pay_status`=6), `total_amount`, 0)) as `total_return_amount`"),
            'pay_status',
            DB::raw("COUNT(`total_amount`) as `total_amount_count`"),
            'refund_amount' //分润金额
        ])
            ->where($where)
            ->where('pay_time', '>=', "$start_time")
            ->where('pay_time', '<=', "$end_time")
            ->where('pay_status_desc', '<>', '会员卡支付成功')
            ->where('company', '<>', 'alipay')
            ->where('company', '<>', 'weixin')
            ->whereNotNull('total_amount')
            ->whereIn('pay_status', ['1', '6'])
            ->whereIn('user_id', $user_ids)
            ->groupBy(['modify_pay_time', 'store_id', 'company', 'rate', 'ways_source', 'pay_status'])
            ->orderBy('modify_pay_time', 'asc');

        if (isset($user_info) && $user_info) {
            $filename = $time.'-'.$user_info->name.'-'.$user_info->level_name.'-分润账单_首付科技.csv';
        } else {
            $filename = $time.'-分润账单_首付科技.csv';
        }
        $tileArray = [
            '交易时间',
//            '代理商名称',
//            '代理商所属',
            '商户名称',
            '交易渠道',
            '费率',
            '成本费率',
            '支付类型',
            '交易金额',
            '商家优惠金额',
            '支付成功金额',
            '退款金额',
            '支付状态',
            '交易笔数',
            '分润金额',
        ];

        $data = $obj->get()->toArray();
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
        fputcsv($fp, $filter_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($data as $item) {
            $item = get_object_vars($item);

//            $item['pay_time'] = date('Y-m-d', strtotime($item['pay_time']));

//            if ($item['level'] == 0) {
//                $item['name'] = '苏州云收易网络科技有限公司';
//                $item['pid_name'] = '';
//            }
//            elseif($item['level'] == 1) {
//                $item['pid_name'] = '收吖旗下';
//            }

            $item['rate'] = $item['rate'] / 100;

            switch ($item['company']) {
                case 'mybank': $item['cost_rate'] = '0.0022';
                    break;
                case 'herongtong': $item['cost_rate'] = '0.0021';
                    break;
                case 'newland': $item['cost_rate'] = '0.0025';
                    break;
                case 'vbill': $item['cost_rate'] = '0.0021';
                    break;
                case 'dlb': $item['cost_rate'] = '0.0023';
                    break;
                case 'tfpay': $item['cost_rate'] = '0.0021';
                    break;
                default: unset($item['cost_rate']);
            }

            if((bccomp($item['rate'], $item['cost_rate'], 3) > 0) && isset($item['rate']) && ($item['pay_status']=='1')){
                $item['refund_amount'] = number_format(($item['total_success_amount']-$item['total_return_amount']-$item['mdiscount_amount_sum'])*(($item['rate']-$item['cost_rate'])), 3);
            } else {
                $item['refund_amount'] = 0.000;
            }

            switch ($item['pay_status']) {
                case '1': $item['pay_status'] = '支付成功';
                    break;
                case '6': $item['pay_status'] = '已退款';
                    break;
                default: unset($item['pay_status']);
            }

            switch ($item['company']) {
                case 'mybank': $item['company'] = '快钱支付';
                    break;
                case 'herongtong': $item['company'] = '和融通';
                    break;
                case 'newland': $item['company'] = '新大陆';
                    break;
                case 'vbill': $item['company'] = '随行付';
                    break;
                case 'dlb': $item['company'] = '哆啦宝';
                    break;
                case 'tfpay': $item['company'] = 'TF通道';
                    break;
                default: unset($item['company']);
            }

            $index++;
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
        ob_end_clean();
    }

    //获取俩时间间隔日期
    public function getDateFromRange($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp) / 86400;

        // 保存每天日期
        $date = array();

        for($i = 0; $i < $days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }
        return $date;
    }

    /**
     * 导出excel
     * 2022-04-07 17:27
     */
    public function UserOrderExcelDownLoad(Request $request){
        $user_id = $this->parseToken()->user_id;
        $user_ids = $this->getSubIds($user_id);

        $store_id = $request->get('store_id', ''); // 系统门店id
        $store = DB::table('stores')->where('store_id', $store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
        $store_name = $store->store_name; // 商户名称
        $store_short_name = DB::table('stores')->where('store_id', $store_id)->value('store_short_name'); // 门店名称
        
        // $id = $store->id;
        // $p_stores = DB::table('stores')->where('pid', $id)->select('store_id')->get(); // 查找总店下的分店
        // // dump($p_stores);die;
        // if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
        //     $store_ids[0] = $store->store_id;
        //     $p_stores = json_decode($p_stores, true);
        //     foreach($p_stores as $k1 => $v1){
        //         $store_ids[] = $v1['store_id'];
        //     }
        // }else{
        //     $store_ids[0] = $store->store_id;
        // }
        // dump($store_ids);die;

        // 判断是本月还是上月
        $month = $request->get('month', '');
        if($month == 1){ // 本月
            $time_start = date('Y-m-01 00:00:00');
            $time_end = date('Y-m-d 23:59:59', strtotime('-1 day'));
        }else{ // 上月
            $time_start = date('Y-m-01 00:00:00', strtotime('-1 month'));
            $time_end = date('Y-m-t 23:59:59', strtotime('-1 month'));
        }
        $date = $this->getDateFromRange($time_start, $time_end); // 获取俩时间间隔日期
        foreach ($date as $k=>$v){
            $table='orders_'.str_replace("-","",$v);
            $timestart = $v . ' 00:00:00';
            $timeend = $v . ' 23:59:59';
            $where[] = ['created_at', '>=', $timestart];
            $where[] = ['created_at', '<=', $timeend];

            $order_data[$k]['date'] = $timestart . ' - 23:59:59'; // 交易日期
            $order_data[$k]['store_name'] = $store_name; // 商户名称
            $order_data[$k]['store_id'] = $store_id. "\t";; // 系统门店id
            $order_data[$k]['store_short_name'] = $store_short_name; // 门店名称
            
            $order_data[$k]['total_sum_success_alipay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['alipay']) // 支付宝
                ->select('total_amount')->sum('total_amount'); // 支付宝交易成功金额
            $order_data[$k]['order_count_success_alipay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['alipay']) // 支付宝
                ->select('total_amount')->count('total_amount'); // 支付宝交易成功笔数

            $order_data[$k]['order_sum_failed_alipay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [6]) // 退款
                ->whereIn('ways_source', ['alipay']) // 支付宝
                ->select('refund_amount')->sum('refund_amount'); // 支付宝交易退款金额



            $order_data[$k]['total_sum_success_weixin'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['weixin']) // 微信
                ->select('total_amount')->sum('total_amount'); // 微信交易成功金额

            $order_data[$k]['order_count_success_weixin'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('user_id', $user_ids)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['weixin']) // 微信
                ->select('total_amount')->count('total_amount'); // 微信交易成功笔数

            $order_data[$k]['order_count_failed_weixin'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [6]) // 退款
                ->whereIn('ways_source', ['weixin']) // 微信
                ->select('refund_amount')->sum('refund_amount'); // 微信交易退款金额



            $order_data[$k]['total_sum_success_unionpay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('user_id', $user_ids)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['unionpay']) // 云闪付
                ->select('total_amount')->sum('total_amount'); // 云闪付交易成功金额

            $order_data[$k]['order_count_success_unionpay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [1]) // 成功
                ->whereIn('ways_source', ['unionpay']) // 云闪付
                ->select('total_amount')->count('total_amount'); // 云闪付交易成功笔数

            $order_data[$k]['order_count_failed_unionpay'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [6]) // 退款
                ->whereIn('ways_source', ['weixin']) // 云闪付
                ->select('refund_amount')->sum('refund_amount'); // 云闪付交易退款金额


            $order_data[$k]['order_counts'] = DB::table($table)->where($where)
                ->where('store_id', $store_id)
                ->whereIn('pay_status', [1]) // 成功+退款
                ->select('total_amount')->sum('total_amount'); // 交易金额

            unset($where);
        }
        $dataArray = array();
        foreach ($order_data as $key=>$val){
            $dataArray[] = $val;
        }
        $where_desc = '';
        $where_desc = $where_desc . $time_start;
        $where_desc = $where_desc . '；终止日期：' . $time_end;

        $filename = '订单导出.csv';
        $s_array = ['起始日期：' . $where_desc];
        $tileArray = ['交易日期', '商户名称', '商户编号', '门店名称', '支付宝交易成功金额', '支付宝交易成功笔数', '支付宝交易退款金额', '微信交易成功金额', '微信交易成功笔数', '微信交易退款金额', '云闪付交易成功金额', '云闪付交易成功笔数', '云闪付交易退款金额', '交易金额'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
//            $item['rate'] = $item['rate'] / 100;
            $index++;
            fputcsv($fp, $item);
        }
        $count = ['数据统计'];
        fputcsv($fp, ['']);
        fputcsv($fp, $count);

        $month_count = ['交易总笔数', '交易总金额', '退款总金额'];
        fputcsv($fp, $month_count);


        $wheres = [];
        $wheres[] = ['created_at', '>=', $time_start];
        $wheres[] = ['created_at', '<=', $time_end];
        
        $count = DB::table('orders')->where($wheres)
            ->where('store_id', $store_id)
            ->whereIn('pay_status', [1]) // 成功+退款
            ->select('total_amount')->count('total_amount'); // 交易总笔数

        $total_amount = DB::table('orders')->where($wheres)
            ->where('store_id', $store_id)
            ->whereIn('pay_status', [1]) // 成功+退款 [1, 6]
            ->select('total_amount')->sum('total_amount'); // 交易总金额

        $refund_amount = DB::table('orders')->where($wheres)
            ->where('store_id', $store_id)
            ->whereIn('pay_status', [6]) // 退款
            ->select('refund_amount')->sum('refund_amount'); // 退款总金额


        fputcsv($fp, [$count, $total_amount, $refund_amount]);

        ob_flush();
        flush();
        ob_end_clean();
    }

    /**
     * 导出二维码excel
     * 2022-04-29 11:04
     */
    public function exportQrcode(Request $request){

        // $user_id = $this->parseToken()->user_id;
        // $user_ids = $this->getSubIds($user_id);
//        dump($user_ids);die;
        // $stores=DB::table('stores')->where('pid','=',0)->get();
        // $stores=json_decode($stores,true);
        // foreach($stores as $k=>$v){
        //     if($v['city_name']=='阜阳市' || strpos($v['store_name'],'阜阳')== true || strpos($v['store_name'],'太和')== true|| strpos($v['store_name'],'阜南')== true|| strpos($v['store_name'],'界首')== true|| strpos($v['store_name'],'颍上')== true|| strpos($v['store_name'],'颍州')== true|| strpos($v['store_name'],'颍东')== true|| strpos($v['store_name'],'临泉')== true|| strpos($v['store_name'],'颍泉')== true){
        //       $data[$k]['store_name']=$v['store_name'];
        //     }
        // }

        $id = $request->get('id', ''); // id

        $cno = DB::table('qr_lists')->where(['id' => $id])->value('cno');

        $code_number = DB::table('qr_list_infos')->where(['cno' => $cno])->select('code_number')->get('code_number');
        $code_number = json_decode($code_number, true);
        // dump($code_number);die;
        foreach($code_number as $k => $v){
            // dump($v['code_number']);die;
            $data[$k]['url'] = 'https://pay.zgjindoufu.com/qr?no=' . $v['code_number'];
            // dump($data);die;
            $data[$k]['code_number'] = $v['code_number'];
        }
        // dump($data);die;

        // $where_desc = '';
        // $where_desc = $where_desc . $time_start;
        // $where_desc = $where_desc . '；终止日期：' . $time_end;

        $filename = '商户收款空码导出.csv';
        // $s_array = ['起始日期：' . $where_desc];
        $tileArray = ['二维码链接', '商户收款空码'];
//        dump($dataArray);die;
//        dump($refund_amount);die;

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition: filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        // fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($data as $item) {
//            $item['rate'] = $item['rate'] / 100;
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    /**
     *
     * 2022-07-08 10:42
     */
    public function lastbill(Request $request){
//        print_r(2);die;
        $user_id = $this->parseToken()->user_id;
        $user_ids = $this->getSubIds($user_id);

        $time_start = date('Y-m-01', strtotime('-1 month'));
        $time_end = date('Y-m-t', strtotime('-1 month'));
//            print_r($time_start);die;

//            $store = DB::table('stores')->whereIn('user_id', $user_ids)->select('store_id')->get();
////        $obj = DB::table('stores')->whereIn('user_id', $user_ids);
////        $this->t = $obj->count();
////        $store = $this->page($obj)->select('store_id', 'store_name')->get();
//            $store = json_decode($store, true);
//            $store = array_column($store, 'store_id');

//            print_r($store);die;

        $where = [];
        $where[] = [ 'c.settling_day', '>=', $time_start ];
        $where[] = [ 'c.settling_day', '<=', $time_end ];

        $data = DB::table('company_day_commission as c')->where($where)->where('c.user_id', $user_id)->leftJoin('stores', 'c.store_id', 'stores.store_id')->select('c.store_id', 'stores.store_name', 'c.company', 'c.total_amount')->get();
        $data = json_decode($data, true);

        foreach($data as $k => $v){
            $data[$k]['store_id'] = $v['store_id'] . "\t";
            $data[$k]['company'] = $this->get_commany_name( $data[$k]['company'] );
        }


//        $this->t = $obj->count();

//        dump($data);die;
//        $data = $this->page($obj)->select('store_id', 'company', 'total_amount')->get();
        $dataArray = $data;

//        foreach($store as $k => $v){
////            dump($v);die;
//            $dataArray[$k]['store_name'] = $v;
//            $dataArray[$k]['alipay'] = DB::table('company_day_commission')->where($where)->where([ 'store_id' => $v, 'company' => 'alipay' ])->sum('refund_amount');
////            dump($dataArray);die;
////            $data[$k]['refund_amount'] = DB::table('stores_day_count')->where($where)->where([ 'store_id' => $v['store_id'] ])->sum('refund_amount');
////            $data[$k]['store_order_count'] = DB::table('stores_day_count')->where($where)->where([ 'store_id' => $v['store_id'] ])->sum('store_order_count');
////            $data[$k]['refund_order_num'] = DB::table('stores_day_count')->where($where)->where([ 'store_id' => $v['store_id'] ])->sum('refund_order_num');
//        }
//        dump($dataArray);die;
//        $dataArray = DB::table('company_day_commission')->where($where)->whereIn('store_id', $store)->select('store_id', 'company', 'total_amount')->get();
////        $this->t = $obj->count();
////        $data = $this->page($obj)->select('store_id', 'company', 'total_amount')->get();
//        $dataArray = json_decode($dataArray, true);

//        print_r($dataArray);die;

//        $dataArray = array();
//        foreach ($data as $key => $val){
//            $dataArray[] = $val;
////            dump($array);
////            fputcsv($fp, $array);
//        }

//        dump($dataArray);die;

        $filename = '上月账单.csv';
        $tileArray = ['商户id', '商户名称', '通道', '收款总额'];
//        dump($dataArray);die;
//        dump($refund_amount);die;

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
//            $item['rate'] = $item['rate'] / 100;
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    /**
     *
     * 2022-07-12 15:56
     */
    function merchant_turnover_last_week(Request $request){
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');
        $store_name = $request->get('store_name', '');

        if( $store_name !== ''){
            $wheres[] = [ 'store_name', 'like', '%' . $store_name . '%' ];
        }

        if( empty($time_start) || empty($time_end) ){
            $this->status = -1;
            $this->message = '请选择时间';
            return $this->format();
        }

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }

        if( empty($time_end) ){
            $time_end = date('Y-m-d H:i:s', time());
        } else {
            if ($time_start != $time_end) {
                $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                if (!$date) {
                    return json_encode([
                        'status' => 2,
                        'message' => '开始时间不能超过结束时间'
                    ]);
                }
            }
        }


        $where[] = ['settling_day', '>=', $time_start];
        $where[] = ['settling_day', '<=', $time_end];
        $wheres[] = ['created_at', '>=', $time_start . ' 00:00:00'];
        $wheres[] = ['created_at', '<=', $time_end . ' 23:59:59'];

        $stores = DB::table('stores')->where('pid', '=', 0)->where($wheres)->select('store_id')->get();
        $stores = json_decode($stores, true);
        $stores = array_column($stores, 'store_id');

        foreach($stores as $k => $v){
            $p_stores = DB::table('stores')->where('pid', $v)->select('store_id')->get(); // 查找总店下的分店
            if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $v;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $store_ids[] = $v1['store_id'];
                }
            }else{
                $store_ids[0] = $v;
            }

            $store_pay_ways[$k] = DB::table('store_pay_ways')->where('store_id', $v)->select('company')->distinct()->get();
            foreach($store_pay_ways[$k] as $key => $val){
                $total_amount = DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where([ 'company' => $val->company ])->where($where)->sum('total_amount');
                $store_name = DB::table('stores')->where('store_id', $v)->select('store_name')->get('store_name');

                $arr = array(
                    'store_id' => $v . "\t",
                    'store_name' => $store_name[0]->store_name,
                    'company' => $this->get_commany_name( $val->company ),
                    'total_amount' => $total_amount
                );
                $dataArray[] = $arr;
            }
        }
//            print_r(2);die;
        if( !isset($dataArray) ){
            $this->status = -1;
            $this->message = '暂无数据';
            return $this->format();
        }

//            print_r($obj);die;


        $filename = '上周新增商户流水.csv';
        $tileArray = ['门店id', '门店名称', '通道', '收款总额(元)'];
//        dump($dataArray);die;
//        dump($refund_amount);die;

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
//            $item['rate'] = $item['rate'] / 100;
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }

// function merchant_turnover_last_week(Request $request){
        
//         $stores = DB::table('lianfuyoupay_stores')->select('store_id','apikey')->get();
//         $stores = json_decode($stores, true);
//         foreach($stores as $k => $v){
//             $store_name = DB::table('stores')->where('store_id', $v['store_id'])->select('store_name')->first('store_name');
//             $configure_channel_fee = DB::table('company_config')->where('store_id', $v['store_id'])->where('company','lianfuyoupay')->select('configure_channel_fee')->first('configure_channel_fee');
//             if(empty($store_name->store_name) || empty($configure_channel_fee->configure_channel_fee)){
//                 $stores[$k]['store_name']='已删除';
//                 $stores[$k]['store_id']=$v['store_id']. "\t";
//                 $stores[$k]['apikey']=$v['apikey']. "\t";
//                 $stores[$k]['rate']='0.00';
//             }else{
//                 $stores[$k]['store_name']=$store_name->store_name;
//                 $stores[$k]['store_id']=$v['store_id']. "\t";
//                 $stores[$k]['apikey']=$v['apikey']. "\t";
//                 $stores[$k]['rate']=$configure_channel_fee->configure_channel_fee;
//             }
//         }

//         $filename = '上周新增商户流水.csv';
//         $tileArray = ['门店id', '邮储商户号','门店名称','费率'];

//         ini_set('memory_limit', '512M');
//         ini_set('max_execution_time', 0);
//         ob_end_clean();
//         ob_start();
//         header("Content-Type: text/csv");
//         header("Content-Disposition:filename=" . $filename);
//         $fp = fopen('php://output', 'w');
//         fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

//         fputcsv($fp, []);
//         fputcsv($fp, $tileArray);

//         $index = 0;
//         foreach ($stores as $item) {
//             $index++;
//             fputcsv($fp, $item);
//         }

//         ob_flush();
//         flush();
//         ob_end_clean();
//     }
    
    /**
     *
     * 2022-07-12 15:56
     */
    function allinpayah_count(Request $request){
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');

        if( empty($time_start) || empty($time_end) ){
            $this->status = -1;
            $this->message = '请选择时间';
            return $this->format();
        }

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }

        if( empty($time_end) ){
            $time_end = date('Y-m-d H:i:s', time());
        } else {
            if ($time_start != $time_end) {
                $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                if (!$date) {
                    return json_encode([
                        'status' => 2,
                        'message' => '开始时间不能超过结束时间'
                    ]);
                }
            }
        }


        $stores = DB::table('mechanism_merchant')->select('merchant_id')->get();
        $stores = json_decode($stores, true);
        $stores = array_column($stores, 'merchant_id');

        foreach($stores as $k => $v){
                $store_name = DB::table('stores')->where('store_id', $v)->select('store_name','id')->first(); //
                $p_stores = DB::table('stores')->where('pid', $store_name->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $v;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id'];
                    }
                }else{
                    $store_ids[0] = $v;
                }
                $where[] = ['created_at', '>=', $time_start.' 00:00:00'];
                $where[] = ['created_at', '<=', $time_end.' 23:59:59'];
                
                $company_config=DB::table('company_config')->where('model', '2')->whereIn('store_id', $store_ids)->select('id','company')->get(); //
                foreach($company_config as $k1=>$v1){
                    if($v1->id=='3750' ||$v1->id=='3749'){
                        continue;
                    }
                    $total_amount = Db::table('orders')->where($where)->where('company', $v1->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1])->select('total_amount')->sum('total_amount');
                     $total_count = Db::table('orders')->where($where)->where('company', $v1->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1])->select('total_amount')->count('total_amount');
                    $fee_amount = Db::table('orders')->where($where)->where('company', $v1->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1])->select('fee_amount')->sum('fee_amount');
                    $arr = array(
                        'store_id' => $v."\t",
                        'store_name' => $store_name->store_name."\t",
                        'company' => $this->get_commany_name($v1->company)."\t",
                        'total_amount' => $total_amount,
                        'total_count' => $total_count,
                        'fee_amount' => $fee_amount,
                    );
                    $dataArray[] = $arr;
                }
                unset($store_ids);
        }
        if( !isset($dataArray) ){
            $this->status = -1;
            $this->message = '暂无数据';
            return $this->format();
        }


        $filename = '通联对账汇总.csv';
        $tileArray = ['门店id', '门店名称', '通道', '收款总额(元)', '收款笔数', '扣款金额(元)'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    
    public function recursion1($user_id,$i = 0){
        $user = DB::table('users')->where([ 'id' => $user_id ])->select('id', 'name', 'pid','level','name')->get();
        $user = json_decode($user,true);
        if( $user[0]['pid'] !== '0'){
            $_SESSION['users'][$i] = $user[0];
            $i++;
            $this->recursion1($user[0]['pid'],$i);
        }else{
            $_SESSION['users'][$i] = $user[0];
        }
        return json_encode((object)$_SESSION['users']);
    }
    /**
     *
     * 2022-07-12 15:56
     */
    function user_stores(Request $request){
            session_start();
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $store_name = $request->get('store_name', '');
            $user = $this->parseToken();
            
            if( empty($time_start) || empty($time_end) ){
                $this->status = -1;
                $this->message = '请选择时间';
                return $this->format();
            }

            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => "时间筛选不能超过 $day 天"
                ]);
            }

            if( empty($time_end) ){
                $time_end = date('Y-m-d H:i:s', time());
            } else {
                if ($time_start != $time_end) {
                    $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                    if (!$date) {
                        return json_encode([
                            'status' => 2,
                            'message' => '开始时间不能超过结束时间'
                        ]);
                    }
                }
            }
            $user_ids = $this->getSubIds($user->user_id);
            $obj = DB::table('stores')->where('pid',0)->whereIn('user_id',$user_ids);
            $stores = $obj->select('store_id')->get();
            $stores = json_decode($stores, true);
            $stores = array_column($stores, 'store_id');
            foreach($stores as $k => $v){
                $store_name = DB::table('stores')->where('store_id', $v)->select('store_name','store_id','id','user_id')->first(); //
                $store_way=DB::table('store_pay_ways')->where('store_id', $store_name->store_id)->where('ways_source', 'weixin')->select('company')->orderBy('sort','desc')->first(); //
                if(isset($store_way->company)){
                    $company_rate=DB::table('company_config')->where('store_id', $store_name->store_id)->where('company', $store_way->company)->select('configure_channel_fee')->first(); //
                }
                unset($_SESSION['users']);
                $users = $this->recursion1($store_name->user_id);
                $users = json_decode($users, true);
                $users = array_reverse($users);
                foreach($users as $k3=>$v3){
                    if($v3['level']>=$user->level &&$v3['level']!='0'){
                        if($v3['level']=='1'){
                            $level1_name=$v3['name'];
                        }elseif ($v3['level']=='2'){
                            $level2_name=$v3['name'];
                        }elseif ($v3['level']=='3'){
                            $level3_name=$v3['name'];
                        }
                    }else{
                        $level1_name='直营商户';
                    }
                }
                if(!isset($level1_name)){
                    $level1_name='无';
                }
                if(!isset($level2_name)){
                    $level2_name='无';
                }
                if(!isset($level3_name)){
                    $level3_name='无';
                }
                $p_stores = DB::table('stores')->where('pid', $store_name->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $v;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id'];
                    }
                }else{
                    $store_ids[0] = $v;
                }
                
                $where[] = ['settling_day', '>=', $time_start];
                $where[] = ['settling_day', '<=', $time_end];
                
                $store_count=DB::table('company_day_commission')->where($where)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_amount')->sum('total_amount'); //
                $total_num=DB::table('company_day_commission')->where($where)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_num')->sum('total_num'); //
                $fee_amount=DB::table('company_day_commission')->where($where)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('fee_amount')->sum('fee_amount'); //
                $commission_money=DB::table('company_day_commission')->where($where)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('commission_money')->sum('commission_money'); //
                $arr = array(
                    'store_id' => $v. "\t",
                    'store_name' => $store_name->store_name,
                    'total_num' => $total_num,
                    'total_amount' => $store_count,
                    'fee_rate' => isset($company_rate->configure_channel_fee)?$company_rate->configure_channel_fee:'0.00',
                    'fee_amount' => $fee_amount,
                    'commission_money' => $commission_money,
                    'level1_name'=>$level1_name,
                    'level2_name'=>$level2_name,
                    'level3_name'=>$level3_name,
                );
                $dataArray[] = $arr;
                unset($store_ids);
                unset($level1_name);
                unset($level2_name);
                unset($level3_name);
            }
        if( !isset($dataArray) ){
            $this->status = -1;
            $this->message = '暂无数据';
            return $this->format();
        }


        $filename = '渠道对账单.csv';
        $tileArray = ['门店id', '门店名称', '交易笔数', '交易总额', '费率', '手续费','佣金','一级代理','二级代理','三级代理'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 获取俩时间间隔日期
    public function getDateFromRanges($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        $days = ($etimestamp - $stimestamp) / 86400; // 计算日期段内有多少天
        $date = array(); // 保存每天日期

        for($i = 0; $i <= $days; $i++){
            $date[] = date( 'Y-m-d', $stimestamp + (86400 * $i) );
        }
        return $date;
    }
    
    // public function get_commany_name($commany_name){
    //     if($commany_name=='alipay'){
    //         $commany_name_zw='官方支付宝';
    //     }else if($commany_name=='weixin'){
    //         $commany_name_zw='官方微信';
    //     }else if($commany_name=='vbill'){
    //         $commany_name_zw='随行付';
    //     }else if($commany_name=='wftpay'){
    //         $commany_name_zw='徽商银行';
    //     }else if($commany_name=='hwcpay'){
    //         $commany_name_zw='汇旺财';
    //     }else if($commany_name=='nongjin'){
    //         $commany_name_zw='农商行';
    //     }else if($commany_name=='abc'){
    //         $commany_name_zw='农行BMP';
    //     }else if($commany_name=='wingpay'){
    //         $commany_name_zw='翼支付';
    //     }else if($commany_name=='lianfuyouzheng'){
    //         $commany_name_zw='';
    //     }else if($commany_name=='pingan'){
    //         $commany_name_zw='平安银行';
    //     }else{
    //         $commany_name_zw='其它';
    //     }
    //     return $commany_name_zw;
    // }
    
    function merchant_company(Request $request){
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $company_id = $request->get('company_id', '');
            $user = $this->parseToken();
            
            if( empty($time_start) || empty($time_end) ){
                $this->status = -1;
                $this->message = '请选择时间';
                return $this->format();
            }

            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => "时间筛选不能超过 $day 天"
                ]);
            }

            if( empty($time_end) ){
                $time_end = date('Y-m-d H:i:s', time());
            } else {
                if ($time_start != $time_end) {
                    $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                    if (!$date) {
                        return json_encode([
                            'status' => 2,
                            'message' => '开始时间不能超过结束时间'
                        ]);
                    }
                }
            }
            $user_ids = $this->getSubIds($user->user_id);
            $obj = DB::table('stores')->where('pid',0)->whereIn('user_id',$user_ids);
            $stores = $obj->select('store_id')->get();
            $stores = json_decode($stores, true);
            $stores = array_column($stores, 'store_id');
            foreach($stores as $k => $v){
                $store_name = DB::table('stores')->where('store_id', $v)->select('store_name','store_id','id','user_id')->first(); //
                $p_stores = DB::table('stores')->where('pid', $store_name->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $v;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id'];
                    }
                }else{
                    $store_ids[0] = $v;
                }
                
                $date=$this->getDateFromRanges($time_start,$time_end);
                foreach($date as $key=>$val){
                    $where[] = ['settling_day', '>=', $val];
                    $where[] = ['settling_day', '<=', $val];
                    if(empty($company_id)){
                        $company_config=DB::table('company_config')->whereIn('store_id', $store_ids)->select('company')->distinct()->get(); //
                       foreach ($company_config as $key1=>$val1){
                           $company_rate=DB::table('company_config')->whereIn('store_id', $store_ids)->where('company', $val1->company)->select('configure_channel_fee')->first(); //
                           $company_names=$this->get_commany_name($val1->company);
                        if(!empty($company_rate)){
                            $store_count=DB::table('company_day_commission')->where($where)->where('company', $val1->company)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_amount')->sum('total_amount'); //
                            $total_num=DB::table('company_day_commission')->where($where)->where('company', $val1->company)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_num')->sum('total_num'); //
                            $fee_amount=DB::table('company_day_commission')->where($where)->where('company', $val1->company)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('fee_amount')->sum('fee_amount'); //
                            $commission_money=DB::table('company_day_commission')->where($where)->where('company', $val1->company)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('commission_money')->sum('commission_money'); //
                            $arr = array(
                                'store_id' => $v. "\t",
                                'store_name' => $store_name->store_name,
                                'date' => $val,
                                'company_names' => $company_names,
                                'total_num' => $total_num,
                                'total_amount' => $store_count,
                                'fee_rate' => isset($company_rate->configure_channel_fee)?$company_rate->configure_channel_fee:'0.00',
                                'fee_amount' => $fee_amount,
                                'commission_money' => $commission_money,
                            );
                            $dataArray[] = $arr;
                        }
                       }
                    }else{
                        $company_rate=DB::table('company_config')->whereIn('store_id', $store_ids)->where('company', $company_id)->select('configure_channel_fee')->first(); //
                        $company_names=$this->get_commany_name($company_id);
                        if(!empty($company_rate)){
                            $store_count=DB::table('company_day_commission')->where($where)->where('company', $company_id)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_amount')->sum('total_amount'); //
                            $total_num=DB::table('company_day_commission')->where($where)->where('company', $company_id)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('total_num')->sum('total_num'); //
                            $fee_amount=DB::table('company_day_commission')->where($where)->where('company', $company_id)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('fee_amount')->sum('fee_amount'); //
                            $commission_money=DB::table('company_day_commission')->where($where)->where('company', $company_id)->where('user_id', $user->user_id)->whereIn('store_id', $store_ids)->select('commission_money')->sum('commission_money'); //
                            
                            $arr = array(
                                'store_id' => $v. "\t",
                                'store_name' => $store_name->store_name,
                                'date' => $val,
                                'company_names' => $company_names,
                                'total_num' => $total_num,
                                'total_amount' => $store_count,
                                'fee_rate' => isset($company_rate->configure_channel_fee)?$company_rate->configure_channel_fee:'0.00',
                                'fee_amount' => $fee_amount,
                                'commission_money' => $commission_money,
                            );
                            $dataArray[] = $arr;
                        }
                    }
                    unset($where);
                }
                unset($store_ids);
            }
        if( !isset($dataArray) ){
            $this->status = -1;
            $this->message = '暂无数据';
            return $this->format();
        }


        $filename = '渠道对账单.csv';
        $tileArray = ['门店id', '门店名称', '交易日期', '通道名称', '交易笔数', '交易总额', '费率', '手续费','佣金'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);

        $index = 0;
        foreach ($dataArray as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 导出平安标记
    public function pingan_tag(Request $request){

        $type = $request->get('type', ''); // 0:未标记 1:使用插件 2:不使用插件
        if($type != '0' && $type != '1' && $type != '2' ){
            print_r('缺少参数');die;
        }
        
        // $pingan_store = DB::table('pingan_stores')->where('type', $type)->select()->get();
        $pingan_store = DB::table('pingan_stores')->select()->get();
        
        // dump($pingan_store);die;
        
        $arr = [];
        foreach($pingan_store as $k => $v){
            $arr[$k]['store_name'] = DB::table('stores')->where([ 'store_id' => $v->store_id ])->value('store_name');
            $arr[$k]['merchant_id'] = $v->merchant_id . "\t";
            
            if($v->type == '0'){
                $arr[$k]['type'] = '未标记';
            }else if($v->type == '1'){
                $arr[$k]['type'] = '使用插件';
            }else if($v->type == '2'){
                $arr[$k]['type'] = '不使用插件';
            }
        }
        // dump($arr);die;
        
        
        $filename = '导出平安标记.csv';
        // $s_array = ['筛选条件：' . '暂不导出'];
        $tileArray = ['门店名称', '平安商户号', '插件是否使用'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        // fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($arr as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 导出平安标记
    public function pingan_chajian(Request $request){
        $date = $request->post('date', '');
        $stores=DB::table('pingan_stores')->where('type','1')->get();
        if (!$date) {
            $where[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
        }else{
            $where[] = ['settling_day', '>=', date('Y-m-01', strtotime($date))];
            $where[] = ['settling_day', '<=', date('Y-m-t', strtotime($date))];
        }
        foreach ($stores as $k=>$v){
            $store=DB::table('stores')->where('store_id',$v->store_id)->first();
            $count=DB::table('service_day_money')->where($where)->where('store_id',$v->store_id)->select('count')->sum('count');
            $order_count=DB::table('service_day_money')->where($where)->where('store_id',$v->store_id)->select('order_count')->sum('order_count');
            $arr[]=array(
                'store_id'=>$v->store_id. "\t",
                'store_name'=>$store->store_name,
                'merchant_id'=>$v->merchant_id. "\t",
                'count'=>$count,
                'order_count'=>$order_count,
            );
        }
        
        
        $filename = '导出平安插件费.csv';
        $tileArray = ['门店ID','门店名称', '平安商户号', '插件费', '订单金额'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        // fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($arr as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 导出签约记录
    public function sign_manage(Request $request){

        $server_stores = DB::table('server_stores')->select()->get();
        
        // dump($server_stores);die;
        
        $arr = [];
        foreach($server_stores as $k => $v){
            // dump($v);die;
            $arr[$k]['store_name'] = DB::table('stores')->where([ 'store_id' => $v->store_id ])->value('store_name');
            $arr[$k]['store_id'] = $v->store_id . "\t";
            
            $v->user_id = DB::table('stores')->where(['store_id' => $v->store_id])->value('user_id');
            $arr[$k]['user_name'] = DB::table('users')->where(['id' => $v->user_id])->value('name');
            
            $arr[$k]['rata_store'] = $v->rata_store;
            
            if($v->status == '0'){
                $arr[$k]['status_name'] = '未签约';
            }else if($v->status == '1'){
                $arr[$k]['status_name'] = '已签约';
            }
            $arr[$k]['company_name'] = $this->get_commany_name($v->company);
            
            $arr[$k]['money_level1'] = $v->money_level1;
            $arr[$k]['money_level2'] = $v->money_level2;
            $arr[$k]['money_level3'] = $v->money_level3;
            
            $arr[$k]['created_at'] = $v->created_at . "\t";
            
            // $data[$k]->user_id = DB::table('stores')->where(['store_id' => $v->store_id])->value('user_id');
            // $data[$k]->user_name = DB::table('users')->where(['id' => $data[$k]->user_id])->value('name');
        }
        // dump($arr);die;
        
        
        $filename = '导出平安标记.csv';
        // $s_array = ['筛选条件：' . '暂不导出'];
        $tileArray = ['门店名称', '门店ID', '代理商', '预充费率', '是否签约', '通道', '提醒额度一', '提醒额度二', '提醒额度三', '签约时间'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        // fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($arr as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 代理门店统计
    public function user_store_count_ExcelDown(Request $request){
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        // 获取传递的参数
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');
        
        

        $user_ids = $this->getSubIds($user_id); // 所有下级代理
        
        if(empty($time_start)){
            $time_start = date('Y-m-d', strtotime("-1 day"));
        }
        if(empty($time_end)){
            $time_end = date('Y-m-d', strtotime("-1 day"));
        }
        if ($time_start != $time_end) {
            $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
            if (!$date) {
                return json_encode([
                    'status' => 2,
                    'message' => '开始时间不能超过结束时间'
                ]);
            }
        }
        // //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }
        if($time_start >= date("Y-m-d",strtotime("+1 day"))){
            return json_encode([
                'status' => 2,
                'message' => '开始时间不能超过今天'
            ]);
        }
        
        if($time_start >= date('Y-m-d', time()) || $time_end >= date('Y-m-d', time()) ){
            return json_encode([
                'status' => 2,
                'message' => '不支持查询今天的统计数据'
            ]);
        }
        
        $where[] = ['created_at', '>=', date('Y-m-d 00:00:00', time())];
        $where[] = ['created_at', '<=', date('Y-m-d 23:59:59', time())];
                    
        $where1[] = ['settling_day', '>=', $time_start];
        $where1[] = ['settling_day', '<=', $time_end];
        
        $users_list = DB::table('users')->where(['pid' => $user_id])->select('id', 'name', 'phone')->get(); // 下级一级的代理列表
        $storearr=[];
        foreach($users_list as $key => $val){
            $user_ids = $this->getSubIds($val->id); // 所有下级代理
            $store_list = DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', 0)->select('store_id', 'store_name', 'people', 'people_phone','id')->get(); // 总店列表
            foreach ($store_list as $r=>$q){
                unset($store_ids);
                $p_stores = DB::table('stores')->where('pid', $q->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $q->store_id;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id']; // 总店+分店
                    }
                }else{
                    $store_ids[0] = $q->store_id; // 总店+分店
                }
                // if($time_start >= date('Y-m-d', time())){ // 查今天
                //     $total_amount = DB::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
                // }else{ // 查每日汇总表
                    $total_amount = DB::table('company_day_commission')->where($where1)->where('user_id', $user_id)->whereIn('store_id', $store_ids)->sum('total_amount');
                // }
                $storearr[]=array('user_name'=>$val->name,'user_phone'=>$val->phone . "\t",'store_id'=>$q->store_id . "\t",'store_name'=>$q->store_name,'store_people'=>$q->people,'store_phone'=>$q->people_phone . "\t",'total_amount'=>$total_amount);
            }
        }
        if($user_id==1){
            $first_user=DB::table('users')->where(['id' => $user_id])->select('id', 'name', 'phone')->first(); // 下级一级的代理列表
            $store_list = DB::table('stores')->where('user_id', $user_id)->where('pid', 0)->select('store_id', 'store_name', 'people', 'people_phone','id')->get(); // 总店列表
            
            foreach ($store_list as $r=>$q){
                unset($store_ids);
                $p_stores = DB::table('stores')->where('pid', $q->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $q->store_id;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id']; // 总店+分店
                    }
                }else{
                    $store_ids[0] = $q->store_id; // 总店+分店
                }
                // if($time_start >= date('Y-m-d', time())){ // 查今天
                //     $total_amount = DB::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
                // }else{ // 查每日汇总表
                    $total_amount = DB::table('company_day_commission')->where($where1)->where('user_id', $user_id)->whereIn('store_id', $store_ids)->sum('total_amount');
                // }
                $storearr[]=array('user_name'=>$first_user->name,'user_phone'=>$first_user->phone . "\t",'store_id'=>$q->store_id . "\t",'store_name'=>$q->store_name,'store_people'=>$q->people,'store_phone'=>$q->people_phone . "\t",'total_amount'=>$total_amount);
            }
        }
        // $data = array_column($storearr, 'total_amount');
        // array_multisort($data, SORT_DESC, $storearr); // 代理按金额排序
        
        $filename = '渠道商户查询.csv';
        $s_array = ['代理-门店统计(订单开始时间：' . $time_start . ';订单结束时间：' . $time_end . ')'];
        $tileArray = ['代理姓名', '代理手机号', '门店id', '门店名称', '商户姓名', '门店手机号', '交易总额'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $s_array);
        // fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($storearr as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
    
    // 门店交易统计 导出
    public function TransactionListExcelDownLoad(Request $request){
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $user_ids = $this->getSubIds($user_id);
        
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');

        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }
        if( empty($time_end) ){
            $time_end = date('Y-m-d H:i:s', time());
        }
        $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
        if (!$date) {
            return json_encode([
                'status' => 2,
                'message' => '开始时间不能超过结束时间'
            ]);
        }
        
        if($time_start >= date('Y-m-d', time()) || $time_end >= date('Y-m-d', time()) ){
            return json_encode([
                'status' => 2,
                'message' => '不支持查询今天的统计数据'
            ]);
        }
        
        $data = [];
        $store = DB::table('stores')->where('pid', '=', 0)->whereIn('user_id', $user_ids)->select('id', 'store_id', 'store_name')->get(); // 门店列表
        
        // if( $time_start == date('Y-m-d', time()) ){ // 今天
        //     $where[] = [ 'created_at', '>=', date('Y-m-d 00:00:00', time()) ];
        //     $where[] = [ 'created_at', '<=', date('Y-m-d 23:59:59', time()) ];

        //     foreach($store as $k => $v){
        //         $p_stores = DB::table('stores')->where('pid', $v->id)->select('store_id')->get(); // 查找总店下的分店
        //         if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
        //             $store_ids[0] = $v->store_id;
        //             $p_stores = json_decode($p_stores, true);
        //             foreach($p_stores as $k1 => $v1){
        //                 $store_ids[] = $v1['store_id'];
        //             }
        //         }else{
        //             $store_ids[0] = $v->store_id;
        //         }
                
        //         $data[$k]['store_name'] = $v->store_name;
        //         $obj = DB::table('orders')->whereIn('store_id', $store_ids)->whereIn('pay_status', [1, 6])->where($where);
                
        //         $data[$k]['store_amount'] = $obj->sum('total_amount');
        //         $data[$k]['store_order_count'] = $obj->count('total_amount');
        //         $data[$k]['weixin_amount'] = 0;
        //         $data[$k]['alipay_amount'] = 0;
        //         unset($store_ids);
        //     }
        // }else{
            $where[] = ['settling_day', '>=', $time_start];
            $where[] = ['settling_day', '<=', $time_end];
            
            foreach($store as $k => $v){
                $data[$k]['store_name'] = $v->store_name;
                $data[$k]['store_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('total_amount');
                $data[$k]['store_order_count'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('total_num');
                $data[$k]['weixin_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('wx_total_amount');
                $data[$k]['alipay_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('zfb_total_amount');
            }
        // }
        
        $edit = array_column($data, 'store_order_count');
        array_multisort($edit, SORT_DESC, $data);
        
        $filename = '门店交易统计.csv';
        $tileArray = ['门店名称', '商户实际收款总额(元)', '总交易笔数(笔)', '微信总交易金额(元)', '支付宝总交易金额(元)'];

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($data as $item) {
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }
}